Skip to content

408. Valid Word Abbreviation 👎

  • Time: $O(n)$
  • Space: $O(1)$
 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
class Solution {
 public:
  bool validWordAbbreviation(const string& word, const string& abbr) {
    int i = 0;  // word's index
    int j = 0;  // abbr's index

    while (i < word.length() && j < abbr.length()) {
      if (word[i] == abbr[j]) {
        ++i;
        ++j;
        continue;
      }
      if (abbr[j] <= '0' || abbr[j] > '9')
        return false;
      int num = 0;
      while (j < abbr.length() && isdigit(abbr[j])) {
        num = num * 10 + abbr[j] - '0';
        ++j;
      }
      i += num;
    }

    return i == word.length() && j == abbr.length();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public boolean validWordAbbreviation(String word, String abbr) {
    int i = 0; // word's index
    int j = 0; // abbr's index

    while (i < word.length() && j < abbr.length()) {
      if (word.charAt(i) == abbr.charAt(j)) {
        ++i;
        ++j;
        continue;
      }
      if (abbr.charAt(j) <= '0' || abbr.charAt(j) > '9')
        return false;
      int num = 0;
      while (j < abbr.length() && Character.isDigit(abbr.charAt(j))) {
        num = num * 10 + abbr.charAt(j) - '0';
        ++j;
      }
      i += num;
    }

    return i == word.length() && j == abbr.length();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def validWordAbbreviation(self, word: str, abbr: str) -> bool:
    i = 0  # word's index
    j = 0  # abbr's index

    while i < len(word) and j < len(abbr):
      if word[i] == abbr[j]:
        i += 1
        j += 1
        continue
      if not abbr[j].isdigit() or abbr[j] == '0':
        return False
      num = 0
      while j < len(abbr) and abbr[j].isdigit():
        num = num * 10 + int(abbr[j])
        j += 1
      i += num

    return i == len(word) and j == len(abbr)