LeetCode#763-划分字母区间

package shuangzhizhen;

import java.util.ArrayList;
import java.util.List;

/*
字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。

 

示例 1:

输入:S = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-labels
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

     解题思路:
            定义一个指针,指向当前字符对应的最右边的相同字符
            然后在[i+1,right]中继续遍历找到最右边的
 */
public class p763 {
    public static List<Integer> partitionLabels(String S) {
        List<Integer>res=new ArrayList<>();
        if(S==null)return res;
        int len=S.length();
        for(int i=0;i<len;){
            int right=len-1;
            while(S.charAt(i)!=S.charAt(right)){//找到和最右一样的字母
                right--;
            }
            //System.out.println("-----------");
            //System.out.println(right);
            //int tmp=len-1;
            for(int j=i+1;j<right;j++){//判断[i+1,right]中有无字母在更右边
                String ss=S.substring(right+1,len);
                if(ss.indexOf(S.charAt(j))!=-1){
                    right=ss.lastIndexOf(S.charAt(j))+right+1;
                }

            }
            res.add(right-i+1);
            i=right+1;


        }
        return res;

    }

    public static void main(String[] args) {
        System.out.println(partitionLabels("aebbedaddc"));
    }
}

  运行结果:

 

在此我用了subString和lastIndexof函数,肯能这个是导致内存消耗和时间消耗过大的原因。

posted @ 2020-07-07 13:51  菜鸡要加油  阅读(177)  评论(0编辑  收藏  举报