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

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

相关推荐
xixihaha13245 分钟前
C++与FPGA协同设计
开发语言·c++·算法
程序员小远30 分钟前
软件测试之功能测试详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
小小怪75031 分钟前
C++中的函数式编程
开发语言·c++·算法
xixixiLucky41 分钟前
编程入门算法题---小明爬楼梯求爬n层台阶一共多少种方法
算法
剑锋所指,所向披靡!1 小时前
数据结构之线性表
数据结构·算法
m0_672703313 小时前
上机练习第49天
数据结构·算法
样例过了就是过了3 小时前
LeetCode热题100 N 皇后
数据结构·c++·算法·leetcode·dfs·深度优先遍历
霖大侠3 小时前
CPAL: Cross-Prompting Adapter With LoRAs forRGB+X Semantic Segmentation
人工智能·深度学习·算法·机器学习·transformer
近津薪荼3 小时前
优选算法——分治(2):快速选择
算法
Z...........3 小时前
(优选算法)斐波那契数列模型
数据结构·算法