Cho chuỗi, tìm chỉ số ký tự đầu tiên chỉ xuất hiện một lần. Ví dụ: "people" → 'o' tại chỉ số 2. Nếu không có → -1.
Giải pháp
Dùng hash map đếm tần suất:
- Tạo frequency map.
- Duyệt chuỗi, cập nhật count.
- Duyệt lại chuỗi, nếu frequency[s[i]] == 1 → trả về i.
- Trả về -1.
Ví dụ
Triển khai Python:
class Solution(object):
def firstUniqChar(self, s):
frequency = {}
for i in s:
if i not in frequency:
frequency[i] = 1
else:
frequency[i] +=1
for i in range(len(s)):
if frequency[s[i]] == 1:
return i
return -1
ob1 = Solution()
print(ob1.firstUniqChar("people"))
print(ob1.firstUniqChar("abaabba")) Đầu vào
"people" "abaabba"
Đầu ra
2 -1