-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path205_Isomorphic_Strings.swift
More file actions
88 lines (66 loc) · 2.15 KB
/
205_Isomorphic_Strings.swift
File metadata and controls
88 lines (66 loc) · 2.15 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
Done 25.09.2025. Revisited: N/A
Given two strings s and t, determine if they are isomorphic.
Two strings s and t are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
Example 1:
Input: s = "egg", t = "add"
Output: true
Explanation:
The strings s and t can be made identical by:
- Mapping 'e' to 'a'.
- Mapping 'g' to 'd'.
Example 2:
Input: s = "foo", t = "bar"
Output: false
Explanation:
The strings s and t can not be made identical as 'o' needs to be mapped to both 'a' and 'r'.
Example 3:
Input: s = "paper", t = "title"
Output: true
Constraints:
1 <= s.length <= 5 * 10^4
t.length == s.length
s and t consist of any valid ascii character.
https://www.youtube.com/watch?v=7yF-U1hLEqQ
Facebook
*/
import Foundation
class P205 {
// MARK: - Option 1 (my). Time: O(n). Memory: O(?)
func isIsomorphic(_ s: String, _ t: String) -> Bool {
// TODO: Incomplete solution
if s.count != t.count { return false }
var charsMapping = [Character: Character]()
for i in 0..<s.count {
if let ch = charsMapping[s[i]] {
if ch != t[i] {
return false
}
} else {
if let ch = charsMapping[t[i]] {
if ch != s[i] {
return false
}
}
charsMapping[s[i]] = t[i]
}
}
return true
}
// MARK: - Option 2 (neetcode). Time: O(n). Memory: O(n)
func isIsomorphic2(_ s: String, _ t: String) -> Bool {
var mapST: [Character: Character] = [:]
var mapTS: [Character: Character] = [:]
for i in 0..<s.count {
let c1 = s[i]
let c2 = t[i]
if (mapST[c1] != nil && mapST[c1] != c2) || (mapTS[c2] != nil && mapTS[c2] != c1) {
return false
}
mapST[c1] = c2
mapTS[c2] = c1
}
return true
}
}