Skip to content

Commit cbea1bf

Browse files
committed
408_Valid_Word_Abbreviation
1 parent a537cbc commit cbea1bf

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import Foundation
2+
3+
class Solution {
4+
func validWordAbbreviation(_ word: String, _ abbr: String) -> Bool {
5+
let wordArray = Array(word), abbrArray = Array(abbr)
6+
var wordPtr = 0, abbrPtr = 0, currentNumber = [String]()
7+
while wordPtr < wordArray.count && abbrPtr < abbrArray.count {
8+
if abbrArray[abbrPtr].isNumber {
9+
if currentNumber.isEmpty && String(abbrArray[abbrPtr]) == "0" {
10+
return false
11+
}
12+
currentNumber.append(String(abbrArray[abbrPtr]))
13+
abbrPtr += 1
14+
} else if currentNumber.count > 0 {
15+
let num = Int(currentNumber.reduce("") { $0 + $1 })
16+
wordPtr += num!
17+
currentNumber.removeAll()
18+
} else if wordArray[wordPtr] == abbrArray[abbrPtr] {
19+
wordPtr += 1
20+
abbrPtr += 1
21+
} else {
22+
return false
23+
}
24+
}
25+
26+
if currentNumber.count > 0 {
27+
let num = Int(currentNumber.reduce("") { $0 + $1 })
28+
wordPtr += num!
29+
currentNumber.removeAll()
30+
}
31+
return (wordPtr == wordArray.count && abbrPtr == abbrArray.count) ? true : false
32+
}
33+
}
34+
35+

0 commit comments

Comments
 (0)