Descripiton Link to heading
1805.number-of-different-integers-in-a-string
Solution Link to heading
Treating numbers as strings, save them in unordered_set
, we need pay attention to pilot zero and the condition which last character is a number.
Code Link to heading
class Solution {
public:
int numDifferentIntegers(string word) {
unordered_set<string> words;
string str;
for (int i = 0; i < word.size(); i++) {
if (str.empty()) {
if (word[i] - '0' <= 9)
str.push_back(word[i]);
} else {
if (word[i] - '0' > 9) {
if (words.find(str) == words.end())
words.insert(str);
str.clear();
} else {
if (str.size() == 1 && str[0] == '0') { // 去除先导0
str.clear();
}
str.push_back(word[i]);
}
}
}
if (!str.empty() && words.find(str) == words.end())
words.insert(str);
return words.size();
}
};