31. 不同整数的计数问题 | 豆包 MarsCode 刷题

36 阅读1分钟

从头到尾把字符串扫一遍。遍历到任何一个字符时只可能处于字母、前导零、整数这三种状态中的一种。用 flg 记录上一个字符的状态,就可以判断当前字符是否会改变状态。状态变为整数时记录位置。状态从整数变为字母时把此前状态为整数的一段插入std::unordered_set。答案即为std::unordered_set.size()

nn 为字符串的长度,MMstd::unordered_set的桶数。
时间复杂度:Θ(n)\Theta(n)
空间复杂度:O(n+M)O(n+M)

代码(C++):

#include <string>
#include <unordered_set>
using namespace std;

int solution(string word) {
    word += 'a';
    unordered_set<string> S;
    int flg = 0;
    for (size_t i = 0, j = 0; i < word.size(); ++i) {
        char c = word[i];
        if (flg == 0) {
            if (c == '0') {
                flg = 1;
            } else if (c > '0' && c <= '9') {
                flg = 2;
                j = i;
            }
        } else if (flg == 1) {
            if (c == '0') {
            } else if (c > '0' && c <= '9') {
                flg = 2;
                j = i;
            } else {
                flg = 0;
                S.insert("");
            }
        } else if (c >= 'a' && c <= 'z') {
            flg = 0;
            S.insert(word.substr(j, i - j));
        }
    }
    return int(S.size());
}