题目描述:
给你一个字符串 word ,该字符串由数字和小写英文字母组成。
请你用空格替换每个不是数字的字符。例如,“a123bc34d8ef34” 将会变成 " 123 34 8 34" 。注意,剩下的这些整数为(相邻彼此至少有一个空格隔开):“123”、“34”、“8” 和 “34” 。
返回对 word 完成替换后形成的 不同 整数的数目。
只有当两个整数的 不含前导零 的十进制表示不同, 才认为这两个整数也不同。
示例 1:
输入:word = “a123bc34d8ef34”
输出:3
解释:不同的整数有 “123”、“34” 和 “8” 。注意,“34” 只计数一次。
示例 2:
输入:word = “leet1234code234”
输出:2
示例 3:
输入:word = “a1b01c001”
输出:1
解释:“1”、“01” 和 “001” 视为同一个整数的十进制表示,因为在比较十进制值时会忽略前导零的存在。
提示:
1 <= word.length <= 1000
word 由数字和小写英文字母组成
方法1:
主要思路:解题链接汇总
(1)确定每一段的数字字符串,使用unodered_set去重;
class Solution {
public:
//将当前分割的字符串存入到unordered_set<string>中;
void get_str(string&str,unordered_set<string>&st){
if(str.size()==0){
return;
}
int index=0;
//去除前置0
while (index < str.size() && str[index] == '0') {
++index;
}
if (index == str.size()) {
st.insert("0");
}
else {
st.insert(str.substr(index));
}
str="";
}
int numDifferentIntegers(string word) {
string str;
unordered_set<string> st;
for (char&ch : word) {
if (ch >= '0'&&ch <= '9') {//获得当前数字字符串
str += ch;
}
else {
get_str(str,st);
}
}
get_str(str,st);
return st.size();
}
};
//使用go 实现
func helper(str string,mp map[string]struct{}){
if len(str)>0 {
index := 0
for index<len(str)&&str[index]=='0' {
index++
}
if index==len(str) {
mp["0"]=struct{}{}
}else {
mp[str[index:]]=struct{}{}
}
}
}
func numDifferentIntegers(word string) int {
mp := map[string]struct{}{}
str := ""
for _,ch := range word {
if ch>='0'&&ch<='9' {
str+=string(ch)
}else{
helper(str,mp)
str=""
}
}
helper(str,mp)
return len(mp)
}