描述 Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.
Examples:
s = "leetcode"return 0.s = "loveleetcode",return 2.Note: You may assume the string contain only lowercase letters.
分析 考慮到題目中只有小寫(xiě)字母,可以采用桶計(jì)數(shù)的思路。
代碼
class Solution {public: int firstUniqChar(string s) { int alpha[26] = {0}; const int n = s.size(); for (int i = 0; i < n; ++i) alpha[s[i] - 'a']++; for (int i = 0; i < n; ++i) if (alpha[s[i] - 'a'] == 1) return i; return -1; }};新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注