Skip to content

Commit 1e33f21

Browse files
authored
Create valid-word-abbreviation.cpp
1 parent 73f6209 commit 1e33f21

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

C++/valid-word-abbreviation.cpp

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
bool validWordAbbreviation(string word, string abbr) {
7+
int i = 0, digit = 0;
8+
for (const auto& c : abbr) {
9+
if (isdigit(c)) {
10+
if (digit == 0 && c == '0') {
11+
return false;
12+
}
13+
digit *= 10;
14+
digit += c - '0';
15+
} else {
16+
if (digit) {
17+
i += digit;
18+
digit = 0;
19+
}
20+
if (i >= word.length() || word[i++] != c) {
21+
return false;
22+
}
23+
}
24+
}
25+
if (digit) {
26+
i += digit;
27+
}
28+
return i == word.length();
29+
}
30+
};

0 commit comments

Comments
 (0)