You are provided with a string word
that consists of digits and lowercase English letters. You need to return the number of distinct integers present in the word
. An integer is a contiguous sequence of digits within the string. Leading zeros are ignored when determining distinct integers.
Example 1:
Input: word = "a123bc34d8ef34"
Output: 3
Explanation: The integers found in the string are "123", "34", "8", and "34".
The distinct integers are "123", "34", and "8".
Example 2:
Input: word = "leet1234code234"
Output: 2
Explanation: The integers found in the string are "1234" and "234".
Example 3:
Input: word = "a1b01c001"
Output: 1
Explanation: The integers found in the string are "1", "01", and "001".
The distinct integers when leading zeros are ignored are all "1".
Q: Can the string contain any non-digit, non-lowercase characters (e.g., special characters)? A: No, the problem specifies the string contains only digits and lowercase English letters.
Q: What should be returned if there are no digits in the string? A: If there are no digits in the string, the function should return 0 as there are no integers present.
def numDifferentIntegers(word: str) -> int:
import re
# Use regex to find all contiguous sequences of digits
digit_sequences = re.findall(r'\d+', word)
# Convert sequences to integers to ignore leading zeros
unique_integers = {int(seq) for seq in digit_sequences}
# Return the number of unique integers
return len(unique_integers)
# Example usage:
# print(numDifferentIntegers("a123bc34d8ef34")) # Output: 3
# print(numDifferentIntegers("leet1234code234")) # Output: 2
# print(numDifferentIntegers("a1b01c001")) # Output: 1
re.findall(r'\d+', word)
scans the string once, which is O(n), where n is the length of the string.Overall, the time complexity is O(n), where n is the length of the string. This ensures the solution is efficient even for relatively long strings.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?