字符串中不同整数的数目【LC1805】
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.
终于有简单题了,类似的题还挺多,总结可以看这里
- 思路:使用双指针定位字符串中整数的起始位置和结束位置,去除前导0后,将该整数放入哈希表中,最后返回哈希表的大小即可。
。如果左指针为字母,那么右移左指针,左指针为整数的起始位置
。如果右指针为数字,那么右移右指针,右指针为整数的结束位置+1
- 实现
class Solution { public int numDifferentIntegers(String word) { Set<String> set = new HashSet<>(); int len = word.length(); int l = 0; int r = 0; while (l < len && r < len){ // 找到左边界 while (l < len && word.charAt(l) >= 'a' && word.charAt(l) <= 'z'){ l++; } if (l == len){ break; } // 找到右边界 r = l; while ( r < len && word.charAt(r) >= '0' && word.charAt(r) <= '9') { r++; } // 去除前导0 while (l != r && word.charAt(l) == '0'){ l++; } String num = word.substring(l, r); set.add(num); l = r + 1; } return set.size(); } }
。复杂度
- 时间复杂度:O ( n )
- 空间复杂度:O ( n )