字符串中的第一个唯一字符
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = "leetcode"
返回 0
s = "loveleetcode"
返回 2
从此可引申思考哈希表
#include <string> #include <iostream> #include <unordered_map> #include <vector> using namespace std; class Solution { public: int firstUniqChar(string s) { int a[26] = {0}; for (int i = 0; s[i]; ++i) { a[s[i] - 'a']++; } for (int i = 0; s[i]; ++i) { if (a[s[i] - 'a'] == 1) return i; } return -1; } }; int main() { string a = "leetcodeadl"; Solution s; cout << s.firstUniqChar(a) << endl; }
浙公网安备 33010602011771号