Number of Different Integers in a String
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| class Solution:
def numDifferentIntegers(self, word: str) -> int:
for ch in word:
# if the character is a letter, replace it with a space
if ch.isalpha():
word = word.replace(ch, ' ')
# split the modified string into a list of numbers
numbers = word.split()
# create a set to store the unique numbers
unique_numbers = set()
for num in numbers:
# remove leading zeros from each number and add it to the set
stripped_num = num.lstrip('0')
unique_numbers.add(stripped_num)
# return the count of unique numbers
return len(unique_numbers)
|
This code first replaces all letters in the string with spaces. Then it splits the modified string into a list of numbers. For each number in this list, it removes leading zeros and adds the resulting number to a set, which automatically removes duplicates. Finally, it returns the count of unique numbers in the set.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| class Solution:
def numDifferentIntegers(self, word: str) -> int:
s = {""}
i = 0
j = 0
while j <= len(word):
if j < len(word) and word[j].isdigit():
if i < j and word[i] == '0':
i += 1
else:
s.add(word[i:j])
i = j + 1
j += 1
return len(s) - 1
|
This code utilizes the concept of a sliding window. The window starts at index 0 and ends at the index where a non-digit character is found. The code ensures that leading zeros are skipped when adding a number to the set s
. As a result, each distinct number (without leading zeros) is stored exactly once in s
, which allows the function to return the count of distinct numbers by returning the size of the set s
minus 1 (to exclude the empty string).