Number of Different Integers in a String

easy string hash set

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).

Inputword = "a123bc34d8ef34"
Output3
The numbers are 123, 34, 8, 34 → distinct values {123, 34, 8} → 3.

def 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();
}
Time: O(n) Space: O(n)