forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValidWordAbbreviation.swift
43 lines (36 loc) · 1.21 KB
/
ValidWordAbbreviation.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
38
39
40
41
42
43
/**
* Question Link: https://leetcode.com/problems/valid-word-abbreviation/
* Primary idea: Go through both string and compare characters or skip by the number
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class ValidWordAbbreviation {
func validWordAbbreviation(_ word: String, _ abbr: String) -> Bool {
var i = 0, j = 0
let word = Array(word), abbr = Array(abbr)
while i < word.count && j < abbr.count {
if abbr[j].isNumber {
// edge case: "abbc" vs. "a02c"
if abbr[j] == "0" {
return false
}
let start = j
while j < abbr.count && abbr[j].isNumber {
j += 1
}
let end = j - 1
i += Int(String(abbr[start...end]))!
} else {
if abbr[j] != word[i] {
return false
} else {
i += 1
j += 1
}
}
}
// edge case: "hi" vs. "hi1"
return i == word.count && j == abbr.count
}
}