給一個字串,找出第一個沒有重複的字符位置,如果沒有則回傳 -1 。
沒有重複,代表該字符的計數為 1,只要找出最早的計數為 1 個字符。
最快的情形是跑一遍 N ,再挑出符合的,沒有那就是 -1 。
Python
class Solution:
def firstUniqChar(self, s: str) -> int:
import collections
counter = collections.Counter(s)
for key in counter:
if counter[key] == 1: return s.index(key)
return -1
C#
public class Solution {
public int FirstUniqChar(string s) {
var counter = new Dictionary();
foreach(var c in s)
{
counter[c] = 1 + (counter.ContainsKey(c) ? counter[c] : 0);
}
foreach(var item in counter)
{
if(item.Value == 1)
{
return s.IndexOf(item.Key);
}
}
return -1;
}
}