763. 划分字母区间

//20220406
题目描述:字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。
题目链接:点我

解题思路:

  • 使用贪心策略,贪婪的策略在于尽早结束当前片段(不断更新当前片段结束的坐标)
  • 具体来说就是,使用end start两个指针,以及flag数组(用于记录每个字母最后出现的位置),在遍历的途中,不断更新end的位置,如果遍历index等于end,说明当前片段结束,开始下一片段的寻找
class Solution {
    public List<Integer> partitionLabels(String s) {
        int[] flag= new int[26];
        for(int i = 0;i<s.length();++i){
            flag[s.charAt(i)-'a'] = i;//记录最后出现的位置
        }
        int start=0;int end = 0;
        List<Integer> res = new ArrayList<>();
        for(int i = 0;i<s.length();++i){
            end = Math.max(end,flag[s.charAt(i)-'a']);//获取当前片段元素最终出现的位置
            if(i==end){//说明这一个片段已经结束了
                res.add(end-start+1);//加入片段长度
                start = i+1;
                end = i+1;
            }
        }
        return res;
    }
}
posted @ 2022-04-06 12:04  醉生梦死_0423  阅读(15)  评论(0编辑  收藏  举报