暴力解法
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();
}
};