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

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

相关推荐
Dlrb12111 小时前
C语言-指针数组与数组指针
c语言·数据结构·算法·指针·数组指针·指针数组·二级指针
WL_Aurora1 小时前
Python 算法基础篇之集合
python·算法
平行侠1 小时前
A15 工业路由器IP前缀高速检索与内存压缩系统
网络·tcp/ip·算法
阿旭超级学得完2 小时前
C++11包装器(function和bind)
java·开发语言·c++·算法·哈希算法·散列表
li星野2 小时前
位运算 & 数学 & 高频进阶九题通关(Python + C++)
c++·python·学习·算法
jerryinwuhan3 小时前
hello算法,简单讲(1)
算法·排序算法
y = xⁿ3 小时前
20天速通LeetCodeday15:BFS广度优先搜索
算法·宽度优先
400分3 小时前
吃透RAG核心-----语义检索与关键字检索底层原理
算法·架构
目黑live +wacyltd3 小时前
算法备案:常见驳回原因与应对策略
人工智能·算法
磊 子3 小时前
多态类原理+四种类型转换+异常处理
开发语言·c++·算法