You are given a string word that consists of digits and lowercase English letters.
You will replace every non-digit character with a space. For example, "a123bc34d8ef34" will become " 123 34 8 34". Notice that you are left with some integers that are separated by at least one space: "123", "34", "8", and "34".
Return the number of different integers after performing the replacement operations on word.
Two integers are considered different if their decimal representations without any leading zeros are different.
Example 1:
Input: word = "a123bc34d8ef34" Output: 3 Explanation: The three different integers are "123", "34", and "8". Notice that "34" is only counted once.
Example 2:
Input: word = "leet1234code234" Output: 2
Example 3:
Input: word = "a1b01c001" Output: 1 Explanation: The three integers "1", "01", and "001" all represent the same integer because the leading zeros are ignored when comparing their decimal values.
Constraints:
1 <= word.length <= 1000wordconsists of digits and lowercase English letters.
Solution
import java.util.*;
class Main {
public static int numDifferentIntegers(String word) {
char[] chararray = word.toCharArray();
Set<Integer>set = new HashSet<>();
int sum=-1;
for(int i=0;i<chararray.length;i++)
{
if(Character.isDigit(chararray[i]))
{
if(sum==-1)
sum=0;
sum = sum*10 + (chararray[i] - '0');
}
else
{
chararray[i] = ' ';
if(sum!=-1)
{
set.add(sum);
sum = -1;
}
}
}
if(sum!=-1)
set.add(sum);
return set.size();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word = sc.nextLine();
System.out.println(numDifferentIntegers(word));
}
}// c++
int numDifferentIntegers(string word) {
set<string> s;
string tmp = "";
bool cnt = false;
word.push_back('a');
for(int i=0; i<word.size(); ++i){
if(isdigit(word[i])){
cnt = true;
tmp = tmp + word[i];
if(tmp == "0")
tmp = "";
}
else{
if(cnt)
s.insert(tmp);
tmp = "";
cnt = false;
}
}
return s.size();
}Happy Learning – If you require any further information, feel free to contact me.
![[Solved] Count Integers Number of Different Integers in a String [Solved] Count Integers Number of Different Integers in a String](https://realcoder.techss24.com/wp-content/uploads/2022/12/Solved-Count-Integers-Number-of-Different-Integers-in-a-String.png)
![[Solved] Append for OR STARTERS 73 CodeChef](https://realcoder.techss24.com/wp-content/uploads/2023/01/Solved-Append-for-OR-STARTERS-73-CodeChef-300x200.png)

![[Solved] Snapchat STARTERS 71 CodeChef](https://realcoder.techss24.com/wp-content/uploads/2022/12/Solved-Snapchat-STARTERS-71-CodeChef-300x197.png)