1805. Number of Different Integers in a String
Description
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 <= 1000
word
consists of digits and lowercase English letters.
Solutions
Solution 1: Double Pointers + Simulation
Traverse the string word
, find the start and end positions of each integer, cut out this substring, and store it in the hash set $s$.
After the traversal, return the size of the hash set $s$.
Note, the integer represented by each substring may be very large, we cannot directly convert it to an integer. Therefore, we can remove the leading zeros of each substring before storing it in the hash set.
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string word
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|