Formatted question description: https://leetcode.ca/all/1805.html
1805. Number of Different Integers in a String
Level
Easy
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.
Solution
Use a set to store the integers in the form of strings. Loop over string word
. If a complete integer is found, remove the leading zeros and added the integer into the set. Finally, return the set’s size.
class Solution {
public int numDifferentIntegers(String word) {
Set<String> set = new HashSet<String>();
StringBuffer sb = new StringBuffer();
int length = word.length();
for (int i = 0; i < length; i++) {
char c = word.charAt(i);
if (Character.isDigit(c))
sb.append(c);
else {
if (sb.length() > 0) {
String num = removeLeadingZeroes(sb.toString());
set.add(num);
sb.setLength(0);
}
}
}
if (sb.length() > 0) {
String num = removeLeadingZeroes(sb.toString());
set.add(num);
}
return set.size();
}
public String removeLeadingZeroes(String str) {
int length = str.length();
if (length == 1)
return str;
int start = 0;
while (start < length - 1) {
if (str.charAt(start) != '0')
break;
start++;
}
return str.substring(start);
}
}