Problem#
給字串 s
回傳第一個非重複字元的 index,如果不存在則回傳 -1
測資限制#
- 1≤n≤105
想法#
照題目所述實作即可
AC Code#
Copy
class Solution { public: int firstUniqChar(string s) { int ans = 0; int cnt[26] = {0}; for(char c : s) cnt[c-'a']++; for(int i = 0; i < s.size(); i++) if(cnt[s[i]-'a'] == 1) return i; return -1; } };
- 時間複雜度: O(n)
- 空間複雜度: O(1)