1.題目
給定一個字符串,找到它的第一個不重複的字符,並返回它的索引。如果不存在,則返回 -1。
案例:
s = “leetcode” 返回 0.
s = “loveleetcode”, 返回 2.
點擊跳轉原題
2.思路
建立數組用於存放26個字母的數量;
把數組內值爲1的對應字符串中的下標輸出即可。
3.代碼
class Solution {
public:
int firstUniqChar(string s) {
int len=s.length();
int arr[26]={0};
for(int i=0;i<len;i++){
arr[s[i]-'a']++;
}
for(int i=0;i<len;i++){
//cout<<arr[i]<<endl;
if(arr[s[i]-'a']==1)
return i;
}
return -1;
}
};
4.優秀案例
利用map計數
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char, int> m;
for (char c : s) ++m[c];
for (int i = 0; i < s.size(); ++i) {
if (m[s[i]] == 1) return i;
}
return -1;
}
};