We use two pointers to scan both the original string and the abbreviation. When we see a digit in the abbreviation, we parse the full number and skip that many characters in the original string. Otherwise, we match characters one by one.
boolvalidWordAbbreviation(string word, string abbr) {
int i =0, j =0, n = word.size(), m = abbr.size();
while (i < n && j < m) {
if (isdigit(abbr[j])) {
if (abbr[j] =='0') return false;
int num =0;
while (j < m && isdigit(abbr[j])) {
num = num *10+ (abbr[j] -'0');
j++;
}
i += num;
} else {
if (i >= n || word[i] != abbr[j]) return false;
i++; j++;
}
}
return i == n && j == m;
}
publicbooleanvalidWordAbbreviation(String word, String abbr) {
int i = 0, j = 0;
while (i < word.length() && j < abbr.length()) {
if (Character.isDigit(abbr.charAt(j))) {
if (abbr.charAt(j) =='0') returnfalse;
int num = 0;
while (j < abbr.length() && Character.isDigit(abbr.charAt(j))) {
num = num * 10 + (abbr.charAt(j) -'0');
j++;
}
i += num;
} else {
if (i >= word.length() || word.charAt(i) != abbr.charAt(j)) returnfalse;
i++;
j++;
}
}
return i == word.length() && j == abbr.length();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
funvalidWordAbbreviation(word: String, abbr: String): Boolean {
var i = 0; var j = 0while (i < word.length && j < abbr.length) {
if (abbr[j].isDigit()) {
if (abbr[j] =='0') returnfalsevar num = 0while (j < abbr.length && abbr[j].isDigit()) {
num = num * 10 + (abbr[j] - '0')
j++ }
i += num
} else {
if (i >= word.length || word[i] != abbr[j]) returnfalse i++ j++ }
}
return i == word.length && j == abbr.length
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
defvalidWordAbbreviation(word: str, abbr: str) -> bool:
i = j =0while i < len(word) and j < len(abbr):
if abbr[j].isdigit():
if abbr[j] =='0':
returnFalse# leading zero not allowed num =0while j < len(abbr) and abbr[j].isdigit():
num = num *10+ int(abbr[j])
j +=1 i += num
else:
if i >= len(word) or word[i] != abbr[j]:
returnFalse i +=1 j +=1return i == len(word) and j == len(abbr)
pubfnvalid_word_abbreviation(word: &str, abbr: &str) -> bool {
let (mut i, mut j) = (0, 0);
let w = word.as_bytes();
let a = abbr.as_bytes();
while i < w.len() && j < a.len() {
if a[j].is_ascii_digit() {
if a[j] ==b'0' { returnfalse; }
letmut num =0;
while j < a.len() && a[j].is_ascii_digit() {
num = num *10+ (a[j] -b'0') asusize;
j +=1;
}
i += num;
} else {
if i >= w.len() || w[i] != a[j] { returnfalse; }
i +=1; j +=1;
}
}
i == w.len() && j == a.len()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
functionvalidWordAbbreviation(word: string, abbr: string):boolean {
leti=0, j=0;
while (i<word.length&&j<abbr.length) {
if (abbr[j] >='0'&&abbr[j] <='9') {
if (abbr[j] ==='0') returnfalse;
letnum=0;
while (j<abbr.length&&abbr[j] >='0'&&abbr[j] <='9') {
num=num*10+ Number(abbr[j]);
j++;
}
i+=num;
} else {
if (i>=word.length||word[i] !==abbr[j]) returnfalse;
i++;
j++;
}
}
returni===word.length&&j===abbr.length;
}