-
Notifications
You must be signed in to change notification settings - Fork 897
Expand file tree
/
Copy pathFirstUniqueCharacterInString.swift
More file actions
42 lines (33 loc) · 1.09 KB
/
FirstUniqueCharacterInString.swift
File metadata and controls
42 lines (33 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Question Link: https://leetcode.com/problems/first-unique-character-in-a-string/
* Primary idea: Keep track of existence of each character in the string
*
* Note: The maximum space of the dictionary is 26, so space complexity is O(1)
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class FirstUniqueCharacterInString {
func firstUniqChar(_ s: String) -> Int {
var uniqueCharactersIndex = -1
guard s.count > 0 else {
return uniqueCharactersIndex
}
var hashTable = [Character:Int]()
for eachChar in s {
if let countExist = hashTable[eachChar] {
hashTable[eachChar] = countExist + 1
} else {
hashTable[eachChar] = 1
}
}
for (index,eachChar) in s.enumerated() {
let count = hashTable[eachChar]
if count == 1 {
uniqueCharactersIndex = index
break
}
}
return uniqueCharactersIndex
}
}