Skip to content

Commit

Permalink
[String] Add a solution to Valid Word Abbreviation
Browse files Browse the repository at this point in the history
soapyigu committed Feb 2, 2020
1 parent 43e2df4 commit eff753a
Showing 2 changed files with 45 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@
![Leetcode](./logo.png?style=centerme)

## Progress
[Problem Status](#problem-status) shows the latest progress to all 1000+ questions. Currently we have 320 completed solutions. Note: questions with ♥ mark means that you have to **Subscript to premium membership** of LeetCode to unlock them.
[Problem Status](#problem-status) shows the latest progress to all 1000+ questions. Currently we have 321 completed solutions. Note: questions with ♥ mark means that you have to **Subscript to premium membership** of LeetCode to unlock them.

## Contributors

@@ -104,6 +104,7 @@
[Fizz Buzz](https://leetcode.com/problems/fizz-buzz/)| [Swift](./String/FizzBuzz.swift)| Easy| O(n)| O(1)|
[First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/)| [Swift](./String/FirstUniqueCharacterInString.swift)| Easy| O(n)| O(1)|
[Keyboard Row](https://leetcode.com/problems/keyboard-row/)| [Swift](./String/KeyboardRow.swift)| Easy| O(nm)| O(n)|
[Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation/)| [Swift](./String/ValidWordAbbreviation.swift)| Easy| O(n)| O(n)|
[Valid Palindrome](https://leetcode.com/problems/valid-palindrome/)| [Swift](./String/ValidPalindrome.swift)| Easy| O(n)| O(n)|
[Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/)| [Swift](./String/ValidPalindromeII.swift)| Easy| O(n)| O(n)|
[Detect Capital](https://leetcode.com/problems/detect-capital/)| [Swift](./String/DetectCapital.swift)| Easy| O(n)| O(1)|
43 changes: 43 additions & 0 deletions String/ValidWordAbbreviation.swift
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
}
}

0 comments on commit eff753a

Please sign in to comment.