zoukankan      html  css  js  c++  java
  • 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函数,肯能这个是导致内存消耗和时间消耗过大的原因。

  • 相关阅读:
    KMP算法
    数据库建立索引为什么会加快查询速度
    腾讯2014实习生4月20日笔试题(分析与解答)
    智能指针auto_ptr & shared_ptr
    用C++实现一个不能被继承的类
    2014金山笔试_编写一个数组类 MyVector
    TCP分组交换详解
    子网掩码的计算
    服务器端 安装svn
    yii2之ActiveForm表单使用
  • 原文地址:https://www.cnblogs.com/jifeng0902/p/13260369.html
Copyright © 2011-2022 走看看