-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path408. Valid Word Abbreviation.java
46 lines (41 loc) · 1.46 KB
/
408. Valid Word Abbreviation.java
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class Solution {
public boolean validWordAbbreviation(String word, String abbr) {
if (word.length() < abbr.length()) { // guard against "hi" vs "hi0"
return false;
}
int i = 0;
StringBuilder w = new StringBuilder();
int r = 0;
while (i < abbr.length()) {
Character c = abbr.charAt(i);
if (c >= 'a' && c <= 'z') {
r = 0;
w.append(abbr.charAt(i));
i++;
} else {
if (c == '0') { return false; } // guard against "hi" vs "02"
while (c < 'a' || c > 'z') {
r = r * 10 + (c - '0');
if (++i == abbr.length()) { break; }
c = abbr.charAt(i);
}
if (r <= word.length()) {
for (int j = 0; j < r; j++) {
w.append("-");
}
} else { return false; } // guard against "hello" vs "99999"
}
}
String w_rd = new String(w);
if (word.length() != w_rd.length()) {
return false;
} else {
for (int j = 0; j < word.length(); j++) {
if (word.charAt(j) != '-' && w_rd.charAt(j) != '-' && word.charAt(j) != w_rd.charAt(j)) {
return false;
}
}
}
return true;
}
}