一刷 07/2022
Version #1 Iteration
Time O(N)
Space O(1)
class Solution {
public boolean validWordAbbreviation(String word, String abbr) {
int pw = 0, pa = 0;
int num = 0;
while (pw < word.length() && pa < abbr.length()) {
while (pa < abbr.length() && Character.isDigit(abbr.charAt(pa))) {
char c = abbr.charAt(pa);
if (c == '0' && num == 0) {
return false;
}
num = num * 10 + (c - '0');
pa++;
}
pw += num;
num = 0;
if (pw >= word.length() || pa >= abbr.length()) {
break;
}
if (word.charAt(pw) != abbr.charAt(pa)) {
return false;
}
pw++;
pa++;
}
return pw == word.length() && pa == abbr.length();
}
}
No comments:
Post a Comment