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

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

相关推荐
阿豪学编程3 小时前
LeetCode724.:寻找数组的中心下标
算法·leetcode
墨韵流芳4 小时前
CCF-CSP第41次认证第三题——进程通信
c++·人工智能·算法·机器学习·csp·ccf
csdn_aspnet4 小时前
C# 求n边凸多边形的对角线数量(Find number of diagonals in n sided convex polygon)
开发语言·算法·c#
禹中一只鱼5 小时前
【力扣热题100学习笔记】 - 哈希
java·学习·leetcode·哈希算法
凌波粒5 小时前
LeetCode--349.两个数组的交集(哈希表)
java·算法·leetcode·散列表
paeamecium6 小时前
【PAT甲级真题】- Student List for Course (25)
数据结构·c++·算法·list·pat考试
Book思议-6 小时前
【数据结构】栈与队列全方位对比 + C 语言完整实现
c语言·数据结构·算法··队列
SteveSenna6 小时前
项目:Trossen Arm MuJoCo
人工智能·学习·算法
NAGNIP6 小时前
一文搞懂CNN经典架构-DenseNet!
算法·面试
道法自然|~6 小时前
BugCTF黄道十二宫
算法·密码学