forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StrobogrammaticNumber.swift
38 lines (32 loc) · 988 Bytes
/
StrobogrammaticNumber.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
34
35
36
37
/**
* Question Link: https://leetcode.com/problems/strobogrammatic-number/
* Primary idea: Two pointers, compare two characters until they are all valid
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class StrobogrammaticNumber {
func isStrobogrammatic(_ num: String) -> Bool {
let numChars = Array(num)
var i = 0, j = num.count - 1
while i <= j {
if isValid(numChars[i], numChars[j]) {
i += 1
j -= 1
} else {
return false
}
}
return true
}
fileprivate func isValid(_ charA: Character, _ charB: Character) -> Bool {
guard let digitA = Int(String(charA)), let digitB = Int(String(charB)) else {
fatalError("Invalid input")
}
if let mirrorA = mirrorDigits[digitA], mirrorA == digitB {
return true
} else {
return false
}
}
}