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

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

相关推荐
孤飞2 小时前
zero2Agent:面向大厂面试的 Agent 工程教程,从概念到生产的完整学习路线
算法
zjeweler3 小时前
“网安+护网”终极300多问题面试笔记-3共3-综合题型(最多)
笔记·网络安全·面试·职场和发展·护网行动
技术专家4 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
Hacker_Nightrain4 小时前
详解Selenium 和Playwright两大框架的不同之处
自动化测试·软件测试·selenium·测试工具·职场和发展
csdn_aspnet4 小时前
C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序
数据结构·算法·c#·排序算法
鹿角片ljp4 小时前
最长回文子串(LeetCode 5)详解
算法·leetcode·职场和发展
paeamecium6 小时前
【PAT甲级真题】- Cars on Campus (30)
数据结构·c++·算法·pat考试·pat
chh5637 小时前
C++--模版初阶
c语言·开发语言·c++·学习·算法
RTC老炮7 小时前
带宽估计算法(gcc++)架构设计及优化
网络·算法·webrtc
dsyyyyy11017 小时前
计数孤岛(DFS和BFS解决)
算法·深度优先·宽度优先