Number of Different Integers in a String

You are given a string word that consists of digits and lowercase English letters.

You will replace every non-digit character with 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

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int numDifferentIntegers(string s)
{

    int n = s.size();
    int i = 0;
    set<stringst;
    while (i < n)
    {
        while (i < n && !(s[i] >= '0' && s[i] <= '9'))
            i++;
        string str = "";
        while (i < n && s[i] >= '0' && s[i] <= '9')
        {
            str += s[i];
            i++;
        }
        if (str.size() > 0)
        {
            int j = 0;
            while (j < str.size() && str[j] == '0')
                j++;
            str = str.substr(j);
            st.insert(str);
        }
    }

    return st.size();
}

int main()
{
    string word = "a123bc34d8ef34";

    cout << numDifferentIntegers(word<< "\n";

    return 0;
}


No comments:

Post a Comment