【重点】【贪心】763.划分字母区间

文章讲述了如何使用贪心策略,通过构建map或数组来记录字符串中每个字符最后一次出现的索引,解决跳跃游戏II中的字符串标签划分问题,提供两种实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

法1:贪心

思路和跳跃游戏II一模一样,只是细节稍有出入,对比记忆!!!

Python

class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        char_dict = dict()
        for i in range(len(s)):
            char_dict[s[i: i+1]] = i
        cur_max = -1
        cur_start = 0
        res = list()
        for i in range(len(s)):
            tmp_char = s[i: i+1]
            cur_max = max(cur_max, char_dict[tmp_char])
            if i == cur_max:
                res.append(cur_max - cur_start + 1)
                cur_start = i + 1
                cur_max = -1
        
        return res

Java

// 使用map记录索引
class Solution {
    public List<Integer> partitionLabels(String s) {
        List<Integer> res = new ArrayList<>();
        Map<Character, Integer> charToLastIndexMap = new HashMap<>();
        for (char c : s.toCharArray()) {
            charToLastIndexMap.put(c, s.lastIndexOf(c));
        }
        int start = 0, maxPos = 0;
        for (int i = 0; i < s.length(); ++i) {
            maxPos = Math.max(maxPos, charToLastIndexMap.get(s.charAt(i)));
            if (i == maxPos) {
                res.add(i - start + 1);
                start = i + 1;
            }
        }
        return res;
    }
}

// 使用数组保存索引
class Solution {
    public List<Integer> partitionLabels(String s) {
        List<Integer> res = new ArrayList<>();
        int[] lastIndexArray = new int[26];
        for (int i = 0; i < s.length(); ++i) {
            lastIndexArray[s.charAt(i) - 'a'] = i;
        }
        int start = 0, maxPos = 0;
        for (int i = 0; i < s.length(); ++i) {
            maxPos = Math.max(maxPos, lastIndexArray[s.charAt(i) - 'a']);
            if (i == maxPos) {
                res.add(i - start + 1);
                start = i + 1;
            }
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值