【每日一题Day48】LC1805字符串中不同整数的数目 | 双指针+哈希表

字符串中不同整数的数目【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) O(n)
      • 空间复杂度: O ( n ) O(n) O(n)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值