import re
class Solution:
def numDifferentIntegers(self, word: str) -> int:
nums = re.findall(r'\d+', word)
normalized = set(num.lstrip('0') or '0' for num in nums)
return len(normalized)
#include <string>
#include <unordered_set>
using namespace std;
class Solution {
public:
int numDifferentIntegers(string word) {
unordered_set<string> s;
int n = word.size();
for (int i = 0; i < n; ) {
if (isdigit(word[i])) {
int j = i;
while (j < n && isdigit(word[j])) ++j;
string num = word.substr(i, j - i);
// Remove leading zeros
int k = 0;
while (k < num.size() - 1 && num[k] == '0') ++k;
s.insert(num.substr(k));
i = j;
} else {
++i;
}
}
return s.size();
}
};
import java.util.HashSet;
import java.util.Set;
class Solution {
public int numDifferentIntegers(String word) {
Set<String> set = new HashSet<>();
int n = word.length();
int i = 0;
while (i < n) {
if (Character.isDigit(word.charAt(i))) {
int j = i;
while (j < n && Character.isDigit(word.charAt(j))) j++;
String num = word.substring(i, j).replaceFirst("^0+", "");
if (num.equals("")) num = "0";
set.add(num);
i = j;
} else {
i++;
}
}
return set.size();
}
}
var numDifferentIntegers = function(word) {
let nums = word.match(/\d+/g);
if (!nums) return 0;
let set = new Set(nums.map(num => num.replace(/^0+/, '') || '0'));
return set.size;
};
word
that contains both lowercase English letters and digits. Your task is to find out how many different integers are present in the string. An integer is defined as a contiguous sequence of digits (0-9) within the string. Leading zeros in an integer should be ignored when determining uniqueness (e.g., "001" and "1" are considered the same integer). Return the count of unique integers found in word
.
\d+
) or by manual iteration.
We use a set because checking if an element exists and adding new elements are both fast operations (on average O(1) time).
Let's walk through the string "a123bc34d8ef34"
:
The set contains {"123", "34", "8"}, so the answer is 3.
For input "a1b01c001"
:
word
. We scan the string once and perform constant-time operations for each character or number found.The key to this problem is accurately extracting and normalizing all digit sequences, then counting the unique ones. Using a set makes uniqueness checks efficient, and handling leading zeros ensures correct grouping. The solution is elegant because it leverages simple string processing and set operations for a linear-time answer.