763. Partition Labels 划分字母区间

https://leetcode-cn.com/problems/partition-labels/description/
A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.

Example 1:
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.

A partition like “ababcbacadefegde”, “hijhklij” is incorrect, because it splits S into less parts.
Note:

S will have length in range [1, 500].
S will consist of lowercase letters (‘a’ to ‘z’) only.

思路:将字符串S中字符最后出现的位置写入map< char, int> , key为字符,value为最后位置.从0开始向后遍历整个串.

class Solution {
public:
vector<int> partitionLabels(string S) {
    vector<int> res; //输出
    map<char, int> last_map; //字符最后出现位置的map
    for (int i = 0; i < S.size(); i++) {
        last_map[S[i]] = i; //构造map
    }
    //从0开始遍历到串末,[start,last]部分为一段划分
    for (int start = 0; start < S.size(); start++) {
        int last = last_map[S[start]]; //last初始化
        for (int i = start; i <= last; i++) { //遍历[start,last]直接的字符,检查是否有新的last
            if (last_map[S[i]] > last) { //若map中存在比当前last还要靠后的记录,更新last
                last = last_map[S[i]];
            }
        }
        res.push_back(last-start+1); //检查last完成后,得到一段划分,将结果写入
        start = last; //更新start
    }
    return res;
}
};

py:
注意,与c++不同,py中for循环的i和range()范围是不会在循环中更改的,只能改用while循环

class Solution:
    def partitionLabels(self, S):
        """
        :type S: str
        :rtype: List[int]
        """
        res = []
        last_map = {}
        for i in range(len(S)):
            last_map[S[i]] = i
        print(last_map)
        start = 0
        while start < len(S):
            last = last_map[S[start]]
            i = start
            while i <= last:
                if last_map[S[i]] > last:
                    last = last_map[S[i]]
                i += 1
            res.append(last-start+1)
            start = last
            start += 1
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值