Processing math: 100%

Leetcode 387 - First Unique Character in a String

題目

Problem#

給字串 s 回傳第一個非重複字元的 index,如果不存在則回傳 -1

測資限制#

  • 1n105

想法#

照題目所述實作即可

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;
}
};
view raw leetcode/387.cpp delivered with ❤ by emgithub
  • 時間複雜度: O(n)
  • 空間複雜度: O(1)