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();
  }
}