1805.字符串中不同整数的数目
链接:1805.字符串中不同整数的数目
难度:Easy
标签:哈希表、字符串
简介:给你一个字符串 word ,该字符串由数字和小写英文字母组成。返回对 word 完成替换后形成的 不同 整数的数目。
题解 1 - cpp
- 编辑时间:2022-12-06
- 内存消耗:6.3MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
    int numDifferentIntegers(string word) {
        unordered_set<string> s;
        for (int i = 0, n = word.size(); i < n; i++) {
            if (!isdigit(word[i])) continue;
            int start = i;
            while (i < n && isdigit(word[i])) i++;
            while (start + 1 < i && word[start] == '0') start++;
            s.insert(word.substr(start, i - start));
        }
        return s.size();
    }
};
题解 2 - cpp
- 编辑时间:2022-03-17
- 内存消耗:6.4MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
   public:
    int numDifferentIntegers(string word) {
        unordered_set<string> s;
        int idx = 0, n = word.size();
        while (idx < n) {
            while (idx < n && isalpha(word[idx])) idx++;
            if (idx == n) break;
            string num = "";
            for (; isdigit(word[idx]); idx++) {
                if (num == "" && word[idx] == '0') continue;
                num += word[idx];
            }
            s.insert(num);
        }
        return s.size();
    }
};