[lintcode] problem 637 – valid word abbreviation

Given a non-empty string word 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”]

Note

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

Example

No.1

Input : s = “internationalization”, abbr = “i12iz4n”

Output : true

No.2

Input : s = “apple”, abbr = “a2e”

Output : false

Code

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
26
public boolean (String word, String abbr) {
int idx = 0;
int count = 0;

for (int i = 0; i < abbr.length(); i++) {
char ch = abbr.charAt(i);

if (Character.isDigit(ch)) {
if (ch == '0' && count == 0)
return false;

count = count * 10 + ch - '0';
}
else {
idx += count;

if (idx >= word.length() || word.charAt(idx) != ch)
return false;

idx++;
count = 0;
}
}

return idx + count == word.length();
}