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.
<Solution>這題是要找沒有重複的字元中,在 string 中第一個出現的
第一種想法
- 準備一個 hash map,記錄所有字元出現的次數
- 按順序去歷遍 string,找到第一個出現次數為1的字元所在的 index
C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int firstUniqChar(string s) { | |
unordered_map<char, int> hashmap; | |
for (const auto &c : s) { | |
hashmap[c]++; | |
} | |
for (int i = 0; i < s.size(); i++) { | |
if (hashmap[s[i]] == 1) return i; | |
} | |
return -1; | |
} | |
}; |
第二種想法(參考資料),會更快一點
- 用兩個指針,指針 cur 指在目前出現次數為1的字元,另一個指針 next 往前找
- 如果 next 指針有更新到 cur 指針指的字元,那麼將 cur 指到下一個出現次數為1的字元
- 如果 cur 指針已經指到尾了,那麼就回傳 -1
C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int firstUniqChar(string s) { | |
if(s.empty()) { | |
return -1; | |
} | |
int hashmap[256] = {0}; | |
int cur = 0, next = 1; | |
const int len = s.length(); | |
hashmap[s[cur]]++; | |
while(next < len) { | |
hashmap[s[next]]++; | |
//>> if current char shows more than one time, | |
//>> then find next char which shows at first time | |
while(cur < len && hashmap[s[cur]] > 1) { | |
++cur; | |
} | |
if(cur == len) { | |
return -1; | |
} | |
else if (hashmap[s[cur]] == 0) { | |
//>> find a char which shows at first time | |
hashmap[s[cur]]++; | |
next = cur; //>> reset next pointer | |
} | |
++next; | |
} | |
return cur; | |
} | |
}; |
沒有留言:
張貼留言