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.(小寫字母)
首先這里假設只有小寫字母,自然想到開一個大小為26的數組,保存每個字母出現的次數,然后在掃描一次字符串,判斷出現次數是否為1,若是則直接返回小標,掃描結束后若還沒有返回,說明沒有字符只出現一次,返回1.
1 int firstUniqChar(char* s) { 2 int m[26] = {0}, len = strlen(s), i; 3 for(i = 0; i < len; i++){ 4 m[s[i] - 'a']++; 5 } 6 for(i = 0; i < len; i++){ 7 if(m[s[i] - 'a'] == 1) 8 return i; 9 } 10 return -1; 11 }
如果沒有假設只包含小寫字母,則可以用map
1 class Solution { 2 public: 3 int firstUniqChar(string s) { 4 int len = s.length(), i; 5 map<char, int> map1; 6 for(i = 0; i < len; i++){ 7 map1[s[i]]++; 8 } 9 for(i = 0; i < len; i++){ 10 if(map1[s[i]] == 1) 11 return i; 12 } 13 return -1; 14 } 15 };