forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[String] Add a solution to Valid Word Abbreviation
- Loading branch information
Showing
2 changed files
with
45 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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 | ||
} | ||
} |