Number of Different Integers in a String Problem
Description
LeetCode Problem 1805.
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.
Example 1:
Input: word = "a123bc34d8ef34"
Output: 3
Explanation: The three different integers are "123", "34", and "8". Notice that "34" is only counted once.
Example 2:
Input: word = "leet1234code234"
Output: 2
Example 3:
Input: word = "a1b01c001"
Output: 1
Explanation: The three integers "1", "01", and "001" all represent the same integer because
the leading zeros are ignored when comparing their decimal values.
Constraints:
1 <= word.length <= 1000wordconsists of digits and lowercase English letters.
Solution
Approach: Scan and Hash Set
Walk through word and find each maximal run of digits. A run can be far too long for any integer type, so keep it as a string, but strip its leading zeros first so that "01" and "1" become the same key. Add each cleaned run to a hash set. A run of only zeros becomes the empty string, which is fine: it still stands for the integer 0 and is counted once.
The answer is the size of the set.
Complexity: O(n) time and O(n) extra space, where n is the length of word.
class Solution:
def numDifferentIntegers(self, word: str) -> int:
s = set()
i, n = 0, len(word)
while i < n:
if word[i].isdigit():
while i < n and word[i] == '0':
i += 1
j = i
while j < n and word[j].isdigit():
j += 1
s.add(word[i:j])
i = j
i += 1
return len(s)