leetcode hot 100 划分字母区间

763. 划分字母区间

已解答

中等

相关标签

相关企业

提示

给你一个字符串 s 。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。

注意,划分结果需要满足:将所有划分结果按顺序连接,得到的字符串仍然是 s

返回一个表示每个字符串片段的长度的列表。

复制代码
class Solution(object):
    def partitionLabels(self, s):
        """
        :type s: str
        :rtype: List[int]
        """
        hashmap = {}
        for index , i in enumerate(s):
            if hashmap.get(i)==None:
                hashmap[i]=[index,index]
            else:
                hashmap[i][1] = index

        # 左臂右弼的()
        start = hashmap[s[0]][0]
        end =  hashmap[s[0]][1]
        ans = []
        for i in range(len(s)):
            if i>end:
                ans.append(end - start+1)
                start = i
                end =  hashmap[s[i]][1]

            if hashmap[s[i]][1] > end:
                end = hashmap[s[i]][1]
        ans.append(end-start+1)
        return ans

这个很简单的贪心算法,也就是遍历一遍,然后看看遍历内的东西最远额能到哪里,如果遍历到达了之前的元素到达的最远,那就是一个划分

相关推荐
AlenTech2 分钟前
647. 回文子串 - 力扣(LeetCode)
算法·leetcode·职场和发展
py有趣6 分钟前
力扣热门100题之合并两个有序链表
算法·leetcode·链表
8Qi821 分钟前
LeetCode热题100--45.跳跃游戏 II
java·算法·leetcode·贪心算法·编程
foundbug9991 小时前
基于STM32的步进电机加减速程序设计(梯形加减速算法)
stm32·单片机·算法
北顾笙9801 小时前
day12-数据结构力扣
数据结构·算法·leetcode
凌波粒1 小时前
LeetCode--454.四数相加 II(哈希表)
算法·leetcode·散列表
漫随流水1 小时前
c++编程:D进制的A+B(1022-PAT乙级)
数据结构·c++·算法
tankeven1 小时前
HJ159 没挡住洪水
c++·算法
美式请加冰2 小时前
斐波那契数列介绍和使用
算法
Redemption2 小时前
嵌软面试每日一阅----Linux驱动之字符设备驱动
linux·面试·职场和发展