Leetcode 1805. Number of Different Integers in a String
Given a string word
composed of digits and lowercase English letters, you need to find the number of different integers in the string. An integer is a contiguous sequence of digits, which may not have leading zeros.
word = "a123bc34d8ef34"
word = "leet1234code234"
#include <iostream>
#include <unordered_set>
#include <string>
using namespace std;
int numDifferentIntegers(string word) {
unordered_set<string> uniqueIntegers;
int n = word.length();
string currentNumber = "";
for (int i = 0; i < n; ++i) {
if (isdigit(word[i])) {
currentNumber += word[i];
} else {
if (!currentNumber.empty()) {
// Remove leading zeros
int index = 0;
while (index < currentNumber.length() && currentNumber[index] == '0') {
++index;
}
string cleanNumber = currentNumber.substr(index);
if (cleanNumber.empty()) {
cleanNumber = "0";
}
uniqueIntegers.insert(cleanNumber);
currentNumber = "";
}
}
}
// Check if there's a number left at the end of the string
if (!currentNumber.empty()) {
int index = 0;
while (index < currentNumber.length() && currentNumber[index] == '0') {
++index;
}
string cleanNumber = currentNumber.substr(index);
if (cleanNumber.empty()) {
cleanNumber = "0";
}
uniqueIntegers.insert(cleanNumber);
}
return uniqueIntegers.size();
}
int main() {
string word;
cin >> word;
cout << numDifferentIntegers(word) << endl;
return 0;
}
word
. We traverse the string once and perform operations of string cleaning, insertion into a set, and comparison, which are all (O(1)) on average per character due to the underlying hash table operations in the set.This solution efficiently identifies and counts the distinct integers within the input string.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?