leetcode 2405. Optimal Partition of String(字符串的最优分割)

在这里插入图片描述

把 s 分割成子字符串,每个子字符串中不能有重复的字母。
问最少可以分成多少个子字符串。

思路:

从左到右遍历 s, 记录substring中已经出现过的字母,出现重复字母时开启新的子字符串。

既然要记录是否出现重复字母,首选hashSet.
因为只有小写英文字母,所以用长度为26的数组代替hashSet.

每次记录下一个substring开始的下标。
不要忘了最后到结尾处也是一个substring.

class Solution {
    int res = 0;
    public int partitionString(String s) {
        int n = s.length();
        int i = 0;
       
        while(i < n) {
            i = partition(s,i,n);
        }
        return res;
    }

    int partition(String s, int st, int e) {
        int[] cnt = new int[26];
        int i = 0;
        for(i = st; i < e; i++) {
            if(cnt[s.charAt(i)-'a'] > 0) {            
                res ++;
                return i;
            }
            cnt[s.charAt(i)-'a'] ++;
        }
        res ++;  //到结尾处也是一个substring
        return i;
    }
}

还有一种更简洁的方法,用整数的bit位代替hashSet.
顺便介绍下,
1 << ‘a’ 相当于1左移1位,同理 1 << ‘b’ 相当于1左移2位,
所以把整数的 1 << 字母 位 置1来表示对应的字母是不是出现过。

hashSet.add(字母)就相当于 整数与(1 << 字母)做异或操作(字母位 置为1)。

    public int partitionString(String s) {
        int map = 0;
        int res = 0;

        for(char ch : s.toCharArray()) {
            if((map & (1 << ch)) > 0) {
                res ++;
                map = 0;
            }
            map ^= (1 << ch);
        }
        return ++res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值