当前位置:网站首页>The number of different integers in the character string of [3 questions (3) per day]

The number of different integers in the character string of [3 questions (3) per day]

2022-06-28 16:58:00 Programmed ape without hair loss 2

subject :

Give you a string word , The string consists of numbers and lowercase letters .

Please replace each character that is not a number with a space . for example ,“a123bc34d8ef34” Will become " 123  34 8  34" . Be careful , The remaining integers are ( Adjacent to each other with at least one space ):“123”、“34”、“8” and “34” .

Return to right word Formed after replacement Different The number of integers .

Only if two integers Without leading zeros The decimal representation of is different , I think these two integers are also different .

Example 1:

Input :word = “a123bc34d8ef34”
Output :3
explain : Different integers are “123”、“34” and “8” . Be careful ,“34” Count only once .
Example 2:

Input :word = “leet1234code234”
Output :2
Example 3:

Input :word = “a1b01c001”
Output :1
explain :“1”、“01” and “001” Treat as a decimal representation of the same integer , Because leading zeros are ignored when comparing decimal values .

Tips :

1 <= word.length <= 1000
word It's made up of numbers and lowercase letters

Ideas :

Use regular handle word Proceed alphabetically split, The resulting array is empty or numeric , Then remove the leading from the number 0

java Code :

class Solution {
    public int numDifferentIntegers(String word) {
       String[] words = word.split("[a-z]+"); 
        Set<String> set = new HashSet<>();
        for(int i=0;i<words.length;i++)
        {
            if(words[i].length()==0) {
                continue;
            }
            int j =0; // Processing leading zeros , Because thinking about ‘00000’ The situation of , So go to the last one before the last one 
            while (words[i].charAt(j)=='0'&&j<words[i].length()-1){
                j++;
            }
            set.add(words[i].substring(j));
        }
        return set.size();
    }
}

原网站

版权声明
本文为[Programmed ape without hair loss 2]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/179/202206281637482231.html