首页 > 其他分享 >1805.number-of-different-integers-in-a-string 字符串中不同整数的数目

1805.number-of-different-integers-in-a-string 字符串中不同整数的数目

时间:2022-12-06 19:33:12浏览次数:73  
标签:integers 1805 word string str words size

问题描述

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

标签:integers,1805,word,string,str,words,size
From: https://www.cnblogs.com/zwyyy456/p/16960288.html

相关文章