# 408. Valid Word Abbreviation

Given a non-empty string s and an abbreviation abbr, return whether the string matches with the given abbreviation.

A string such as "word" contains only the following valid abbreviations:

["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]

Notice that only the above abbreviations are valid abbreviations of the string "word". Any other string is not a valid abbreviation of "word".

Note:
Assume s contains only lowercase letters and abbr contains only lowercase letters and digits.

Example 1:

Given s = "internationalization", abbr = "i12iz4n":

Return true.

Example 2:

Given s = "apple", abbr = "a2e":

Return false.

class Solution {
public:
bool validWordAbbreviation(string word, string abbr) {
int i = 0, j = 0, m = word.size(), n = abbr.size();
while (i < m && j < n) {
if (abbr[j] >= '0' && abbr[j] <= '9') {
if (abbr[j] == '0') return false;
int val = 0;
while (j < n && abbr[j] >= '0' && abbr[j] <= '9') {
val = val * 10 + abbr[j++] - '0';
}
i += val;
} else {
if (word[i++] != abbr[j++]) return false;
}
}
return i == m && j == n;
}
};

class Solution {
public:
bool validWordAbbreviation(string word, string abbr) {
int m = word.size(), n = abbr.size(), p = 0, cnt = 0;
for (int i = 0; i < abbr.size(); ++i) {
if (abbr[i] >= '0' && abbr[i] <= '9') {
if (cnt == 0 && abbr[i] == '0') return false;
cnt = 10 * cnt + abbr[i] - '0';
} else {
p += cnt;
if (p >= m || word[p++] != abbr[i]) return false;
cnt = 0;
}
}
return p + cnt == m;
}
};

Unique Word Abbreviation

Generalized Abbreviation

https://discuss.leetcode.com/topic/61404/concise-c-solution

https://discuss.leetcode.com/topic/61430/java-2-pointers-15-lines

https://discuss.leetcode.com/topic/61353/simple-regex-one-liner-java-python

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation