Leetcode 763:划分字母区间

题目描述:

字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。
示例:
输入:S = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。

思路:
题目的意思是分割后的每个字字符串内的字符都只在该子字符串内出现。所以在分割的时候可以使用贪心,遍历字符串,并找到当前字符出现的最晚位置last,对于当前字符位置与最晚出现位置last之间的字符,寻找它们字符出现的最晚位置,如果最晚位置超过last,更新last并且更新下一个起始位start。将last-start+1内的字符子串长度保存至结果数组中。

代码:

class Solution {
    public List<Integer> partitionLabels(String s) {
        int[] init=new int[26];
        int n=s.length();
        for(int i=0;i<n;i++){
            init[s.charAt(i)-'a']=i;
        }
        List<Integer> res=new ArrayList<Integer>();
        int start=0,end=0;
        for(int i=0;i<n;i++){
            end=Math.max(init[s.charAt(i)-'a'],end);//判断是否需要更新end
            if(i==end){
                res.add(end-start+1);
                start=end+1;
            }
        }
        return res;
    }
}
posted @ 2022-02-07 23:55  Dreamer_szy  阅读(36)  评论(0)    收藏  举报