forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
IsomorphicStrings.swift
33 lines (27 loc) · 1005 Bytes
/
IsomorphicStrings.swift
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
/**
* 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 {
var stDict = [Character: Character]()
var tsDict = [Character: Character]()
let sChars = [Character](s.characters)
let tChars = [Character](t.characters)
guard sChars.count == tChars.count else {
return false
}
for i in 0..<sChars.count {
let sCurrent = sChars[i]
let tCurrent = tChars[i]
if stDict[sCurrent] == nil && tsDict[tCurrent] == nil {
stDict[sCurrent] = tCurrent
tsDict[tCurrent] = sCurrent
} else if stDict[sCurrent] != tCurrent || tsDict[tCurrent] != sCurrent {
return false
}
}
return true
}
}