[LeetCode] 1805. Number of Different Integers in a String
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.
字符串中不同整数的数目。
给你一个字符串 word ,该字符串由数字和小写英文字母组成。
请你用空格替换每个不是数字的字符。例如,"a123bc34d8ef34" 将会变成 " 123 34 8 34" 。注意,剩下的这些整数为(相邻彼此至少有一个空格隔开):"123"、"34"、"8" 和 "34" 。
返回对 word 完成替换后形成的 不同 整数的数目。
只有当两个整数的 不含前导零 的十进制表示不同, 才认为这两个整数也不同。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/number-of-different-integers-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是双指针。这道题是简单题,但是有一些 corner case 需要处理。题意不难理解,就是把 input 字符串里的数字都挑出来,然后返回 unique 的数字的个数。由于需要返回的只是数字的个数,所以我们不需要把字符串转换成数字,这样也就没有整型溢出的问题了。corner case 是比如例子三,对于1, 01, 001,我们都视为 1。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int numDifferentIntegers(String word) { 3 // corner case 4 if (word == null || word.length() == 0) { 5 return 0; 6 } 7 8 // normal case 9 HashSet<String> set = new HashSet<>(); 10 int i = 0; 11 while (i < word.length()) { 12 if (Character.isDigit(word.charAt(i))) { 13 int j = i; 14 StringBuilder sb = new StringBuilder(); 15 while (i < word.length() && Character.isDigit(word.charAt(i))) { 16 sb.append(word.charAt(i)); 17 i++; 18 } 19 while (j < i && word.charAt(j) == '0') { 20 j++; 21 } 22 set.add(word.substring(j, i)); 23 } else { 24 i++; 25 } 26 } 27 return set.size(); 28 } 29 }