Number of Different Integers in a String — LeetCode 1805 Python Solution
EasyHash TableString
- Problem
- #1805
- Pattern
- Hash Map
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given a string word that consists of digits and lowercase English letters. You will replace every non-digit character with a space.
Example
- Input
- word = "a123bc34d8ef34"
- Output
- 3
- Explanation
- The three different integers are "123", "34", and "8". Notice that "34" is only counted once.
Python solution
Python
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)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1805. Number of Different Integers in a String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1805. Number of Different Integers in a String?
- LeetCode 1805. Number of Different Integers in a String is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1805. Number of Different Integers in a String?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1805. Number of Different Integers in a String?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1805. Number of Different Integers in a String cover?
- LeetCode 1805. Number of Different Integers in a String is tagged Hash Table and String on LeetCode.