Strings: Number of Different Integers in a String

Problem Statement:

You are given a string that has numbers.
Now you will replace the characters with space.
Now count the number of distinct number.

Example

Input: word = “hello1234world234”
Output: 2

Why?

Replace char with space
—–1234—–234
We get 2 distinct words.

Solution

Solution is very simple.

We use unordered_Set, to store the distinct character.

Now we are considering “001” “01” “1” as same.

So before we insert the value into the set, we remove the preceeding 0s and then insert.

Solution in C++

#include <algorithm>  
#include <iostream>    
#include <string>
#include <stack>
#include <vector>
#include <unordered_set> 
#include <queue> 

using namespace std;

int num_different_integers(string word) 
{
    int n = word.length();
    unordered_set<string>s;
    int i=0;

    while(i<n)
    {
        //if not digit, continue
        if(isdigit(word[i]) == false)
        {
            i++;
            continue;
        }

        string temp = "";
        //if is digit
        while(i<n && isdigit(word[i]))
        {
            temp+=word[i];
            i++;
        }

        int j=0;
        //remove preceeding 0s
        while(j<temp.length() && temp[j] == '0') 
          j++;

        temp = temp.substr(j);
        s.insert(temp);
    }
    return s.size();
}       

int main() 
{ 
      
string s1 = "hello1234world234"; 
 
cout<<"The number of different integers are "<< num_different_integers(s1)<<endl;

return 0; 
}

Output:

The number of different integers are 2

 

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *