[LeetCode] Number of Different Integers in a String

1805. Number of Different Integers in a String

You are given a string word that consists of digits and lowercase English letters.

You will replace every non-digit character with a space. For example, “a123bc34d8ef34” will become “ 123 34 8 34”. Notice that you are left with some integers that are separated by at least one space: “123”, “34”, “8”, and “34”.

Return the number of different integers after performing the replacement operations on word.

Two integers are considered different if their decimal representations without any leading zeros are different.

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
class Solution {
string substrZero(string &s) {
int pos = 0;
for(; pos < s.length(); pos++) {
if(s[pos] != '0') break;
}

return pos == s.length() ? "0" : s.substr(pos);
}
public:
int numDifferentIntegers(string word) {
unordered_set<string> s;
string str = "";
bool flag = false;
for(int i = 0; i < word.length(); i++) {
if(flag && 'a' <= word[i] && word[i] <= 'z') {
s.insert(substrZero(str));
flag = false;
str = "";
} else if('0' <= word[i] && word[i] <= '9') {
str += word[i];
flag = true;
}
}
if(flag)
s.insert(substrZero(str));

return s.size();
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/28/PS/LeetCode/number-of-different-integers-in-a-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.