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

题目

法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;
    }
}
### 实现划分字母区间的算法 要实现划分字母区间的功能,可以采用贪心算法的思想。通过记录每个字符最后出现的位置,并动态调整当前区间的右边界来完成分区操作。 以下是基于 Python 的具体实现: ```python class Solution: def partitionLabels(self, s: str): # 记录每个字符最后一次出现的索引位置 last_occurrence = {char: idx for idx, char in enumerate(s)} result = [] # 存储最终的结果区间长度 start, end = 0, 0 # 遍历字符串中的每一个字符 for index, char in enumerate(s): # 更新当前区间的结束位置为该字符的最大最后出现位置 end = max(end, last_occurrence[char]) # 如果当前位置等于当前区间的结束位置,则找到了一个完整的区间 if index == end: result.append(end - start + 1) # 添加当前区间的长度到结果列表中 start = end + 1 # 开始新的区间 return result # 返回所有区间的长度列表 ``` #### 示例运行代码 以下是一个具体的例子展示上述函数的工作方式: ```python solution = Solution() input_string = "ababcbacadefegdehijhklij" output = solution.partitionLabels(input_string) print(output) # 输出应为 [9, 7, 8] ``` 此程序会输出 `[9, 7, 8]`,这表明输入字符串被成功划分为三个部分:“ababcbaca”,“defegde” 和 “hijhklij”。 --- ### 关键点解析 1. **记录最后一个位置** 使用字典 `last_occurrence` 来存储每个字符在字符串中的最大索引位置[^2]。这样可以在遍历时快速获取某个字符可能影响的最远范围。 2. **动态更新区间终点** 在每次迭代过程中,比较并更新当前区间的终点 `end`,使其始终指向当前已知范围内字符的最远位置[^3]。 3. **判断区间完成条件** 当前索引到达了当前区间的终点时,说明已经找到一个独立的子串,此时将其长度加入结果集,并重新设置起点以寻找下一个子串[^4]。 4. **时间复杂度分析** 整个过程只需两次线性扫描即可完成:一次用于构建 `last_occurrence` 字典,另一次用于实际划分区间。因此总的时间复杂度为 O(n),空间复杂度也为 O(1)[^5]。 --- ### 注意事项 - 输入字符串仅限于小写英文字母。 - 若输入为空字符串,则返回空列表作为结果。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值