Skip to main content
Back to problems
#1805
Easy Algorithms

Number of different integers in a string

Hash Table String
40.1% acceptance
Feb 25, 2026
663
106
You are given a string word that consists of digits and lowercase English letters. You will replace every non-digit character with a 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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
use std::collections::HashSet;


impl Solution {
  pub fn num_different_integers(word: String) -> i32 {
    let mut set: HashSet<String> = HashSet::new();
    let chars: Vec<char> = word.chars().collect();
    let mut i = 0;
    while i < chars.len() {
      if chars[i].is_ascii_digit() {
        let mut j = i;
        while j < chars.len() && chars[j].is_ascii_digit() {
          j += 1;
        }
        // strip leading zeros
        let s: String = chars[i..j].iter().collect();
        let stripped = s.trim_start_matches('0');
        set.insert(stripped.to_string());
        i = j;
      } else {
        i += 1;
      }
    }
    set.len() as i32
  }
}