问题描述 链接到标题

1805.字符串中不同整数的数目

解题思路 链接到标题

把数字当作字符串处理,存入unordered_set(哈希表)中,注意最后一个字符是数字的情况。

代码 链接到标题

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();
    }
};