LeetCode 每日一题 1805. 字符串中不同整数的数目

暴力解法

class Solution {
public:
    int numDifferentIntegers(string word) {
        word += ' '; // 最后加一个字符,方便判断
        int len = word.length();
        string x;
        set<string> s;
        bool flag = false, st = true; // flag用于跳过字符,st用于跳过前导零
        for (int i = 0; i < len; i ++ ) {
            if (isdigit(word[i])) {
                flag = true;
                char temp = word[i];
                if (temp == '0' && st) { // 遇到前导零就跳过
                    continue;
                } else {
                    st = false;
                    x += temp;
                } 
            } else {
                if (flag) {
                    s.insert(x);
                    cout << x << ' ';
                    x = ""; // 重置x
                }
                flag = false; //重置flag
                st = true; // 重置st
                continue;
            }
        }
        return s.size();
    }
};

双指针+模拟

class Solution {
public:
    int numDifferentIntegers(string word) {
        unordered_set<string> s;
        int len = word.size();
        for (int i = 0; i < len; i ++ ) {
            if (isdigit(word[i])) { // 只有数字进行选择
                int j = i;
                while (j < len && isdigit(word[j])) j ++ ; // 更新数字位数
                while (i < j && word[i] == '0') i ++ ; // 更新前导零位数
                s.insert(word.substr(i, j - i)); // 将去除前导零的子串加入s中
                i = j; // 更新字符串位数
            }
        }
        return s.size();
    }
};

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值