-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathIsomorphicStrings.swift
More file actions
29 lines (24 loc) · 854 Bytes
/
IsomorphicStrings.swift
File metadata and controls
29 lines (24 loc) · 854 Bytes
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
/**
* Question Link: https://leetcode.com/problems/isomorphic-strings/
* Primary idea: Use two dictionaries to help
* Time Complexity: O(n), Space Complexity: O(n)
*/
class IsomorphicStrings {
func isIsomorphic(_ s: String, _ t: String) -> Bool {
guard s.count == t.count else {
return false
}
var stDict = [Character: Character](), tsDict = [Character: Character]()
let s = Array(s), t = Array(t)
for (i, sChar) in s.enumerated() {
let tChar = t[i]
if stDict[sChar] == nil && tsDict[tChar] == nil {
stDict[sChar] = tChar
tsDict[tChar] = sChar
} else if stDict[sChar] != tChar || tsDict[tChar] != sChar {
return false
}
}
return true
}
}