描述 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.
分析 考虑到题目中只有小写字母,可以采用桶计数的思路。
代码
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; }};新闻热点
疑难解答