Number of Different Integers in a String
Problem
You are given a string word that consists of digits and lowercase letters. Replace every non-digit character with a space, leaving a list of number substrings. Return the number of different integers after the substrings are interpreted as numbers (so leading zeros are ignored: "01" and "1" are the same integer).
word = "a123bc34d8ef34"3def num_different_integers(word):
seen = set()
i, n = 0, len(word)
while i < n:
if word[i].isdigit():
j = i
while j < n and word[j].isdigit():
j += 1
num = word[i:j].lstrip("0") or "0"
seen.add(num)
i = j
else:
i += 1
return len(seen)
function numDifferentIntegers(word) {
const seen = new Set();
const n = word.length;
let i = 0;
while (i < n) {
if (word[i] >= "0" && word[i] <= "9") {
let j = i;
while (j < n && word[j] >= "0" && word[j] <= "9") j++;
let num = word.slice(i, j).replace(/^0+/, "");
seen.add(num === "" ? "0" : num);
i = j;
} else i++;
}
return seen.size;
}
class Solution {
public int numDifferentIntegers(String word) {
Set<String> seen = new HashSet<>();
int n = word.length(), i = 0;
while (i < n) {
if (Character.isDigit(word.charAt(i))) {
int j = i;
while (j < n && Character.isDigit(word.charAt(j))) j++;
int k = i;
while (k < j - 1 && word.charAt(k) == '0') k++;
seen.add(word.substring(k, j));
i = j;
} else i++;
}
return seen.size();
}
}
int numDifferentIntegers(string word) {
set<string> seen;
int n = word.size(), i = 0;
while (i < n) {
if (isdigit(word[i])) {
int j = i;
while (j < n && isdigit(word[j])) j++;
int k = i;
while (k < j - 1 && word[k] == '0') k++;
seen.insert(word.substr(k, j - k));
i = j;
} else i++;
}
return seen.size();
}
Explanation
Letters act only as separators between numbers, so the real work is to pull out each maximal run of digits and decide which runs represent the same integer.
We scan the string with an index i. When we hit a digit, we extend a second index j forward while the characters stay digits — that carves out one complete number substring word[i:j]. Non-digit characters are simply skipped.
Two substrings like "34" and "034" name the same integer, so before remembering a chunk we strip its leading zeros. The cleaned form (with at least one digit kept, so "000" becomes "0") goes into a hash set, which automatically discards duplicates.
Because the numbers can be enormous, we keep them as strings rather than parsing to a fixed-width integer — comparing the zero-stripped strings is exact and avoids overflow.
Example: "a123bc34d8ef34" yields chunks 123, 34, 8, 34. After stripping zeros they are still 123, 34, 8, 34; the set ends up {123, 34, 8}, so the answer is 3.