/**
* @param word: a non-empty string
* @param abbr: an abbreviation
* @return: true if string matches with the given abbr or false
*/
public boolean validWordAbbreviation(String word, String abbr) {
// write your code here
if (abbr == null) {
return false;
}
int i = 0;
int j = 0;
char[] wa = word.toCharArray();
char[] aa = abbr.toCharArray();
while (i < wa.length && j < aa.length) {
if (Character.isDigit(aa[j])) {
int adv = 0;
if (aa[j] == '0') {
return false;
}
while (j < aa.length && Character.isDigit(aa[j])) {
adv = adv * 10 + aa[j] - '0';
j++;
}
i = i + adv;
} else {
if (wa[i] != aa[j]) {
return false;
}
i++;
j++;
}
}
return i == wa.length && j == aa.length;
}
下面是九章的in place版本:
public boolean validWordAbbreviation(String word, String abbr) {
int i = 0, j = 0;
while (i < word.length() && j < abbr.length()) {
if (word.charAt(i) == abbr.charAt(j)) {
i++;
j++;
} else if ((abbr.charAt(j) > '0') && (abbr.charAt(j) <= '9')) { //notice that 0 cannot be included
int start = j;
while (j < abbr.length() && Character.isDigit(abbr.charAt(j))) {
j++;
}
i += Integer.valueOf(abbr.substring(start, j));
} else {
return false;
}
}
return (i == word.length()) && (j == abbr.length());
}