- 字符串中不同整数的数目
给你一个字符串 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" 视为同一个整数的十进制表示,因为在比较十进制值时会忽略前导零的存在。
注意:substring(x,y) :截取从下标为x的字符开始,到下标y-1的字符结束 substring(x):截取从下标为x的字符到字符串末尾的字符串
class Solution {
public int numDifferentIntegers(String word) {
int n = word.length();
int flag = 0;//如果当前字符是数字就为1,否则为0
int flag0=0;//如果当前是字符0就标识为1,否则为0.
int head=0;//起始下标
int tail =0;//结尾下标
Set<String> set = new HashSet<>();
int count =0;//计数
for(int i =0 ;i<n;i++){
char ch = word.charAt(i);
if(ch >='0' && ch <='9'){//是数字就用flag进行标记
System.out.println("ch ="+ch);
if(flag == 0){
if(ch !='0'){
flag=1;
flag0=0;
head=i;//记录起始下标
}else
{
flag0=1;
head=i;//记录起始下标
}
}
if(flag ==1 && i == n-1){//单独考虑以数字结尾的情况
tail = i+1;//要注意以数字结尾时候下标的改变
String st=new String(word.substring(head,tail));
if(!set.contains(st)){
set.add(st);
count++;
}
}
if(flag0 ==1 && i == n-1) {//单独考虑以数字结尾的情况
tail = i + 1;//要注意以数字结尾时候下标的改变
String st = new String(word.substring(head, tail));
if (!set.contains(st)) {
set.add(st);
count++;
}
}
}
else{//不是数字
if(flag == 1){
tail = i;//记录结尾下标,i-1是数字的下标
String st= new String(word.substring(head,tail));
if(!set.contains(st)){
set.add(st);
count++;
}
}
if(flag0 == 1){
tail = i;//记录结尾下标,i-1是数字的下标
String st= new String(word.substring(head,tail));
if(!set.contains(st)){
set.add(st);
count++;
}
}
flag=0;//修改标识
flag0=0;//修改标识
}
}
return count;
}
}