LintCode:1045. 分割标签

描述

给出一个由小写字母组成的字符串S。需要将这个字符串分割成尽可能多的部分,使得每个字母最多只出现在一个部分中,并且返回每个部分的长度。

个人思路:采取的贪心策略是,先遍历一次字符串,得到每个字符的结束的位置,第二次遍历字符串时,都将遍历到的字符的结束位置和之前记录的结束位置比较,最后取最远的结束位置,当i遍历到结束位置时,说明符合题目的要求

 

public List<Integer> partitionLabels(String S) {
        // Write your code here
        // Map<Character,Integer> endPosMap = new HashMap<>();
        // for(int i = 0; i<S.length(); i++){
        //     char ch = S.charAt(i);
        //     endPosMap.put(ch, i);            
        // }

        int[] endPosMap=new int[26];
		for(int i=0;i<S.length();i++){
			endPosMap[S.charAt(i)-'a']=i;
		}

        int lastEndPos = 0;
        int lastStartPos = 0;
        List<Integer> result = new ArrayList<>();
        
        for (int i = 0; i < S.length(); i++) {
            char ch = S.charAt(i);
            int endPos = endPosMap[ch - 'a'];

            if(i == 0)
                lastEndPos = endPos;

            if (i > lastEndPos){
                lastEndPos = endPos;
            }

            if(i < lastEndPos && endPos > lastEndPos){
                lastEndPos = endPos;
            }
            
            if(i == lastEndPos){
                result.add(lastEndPos - lastStartPos + 1);
               // r.add(S.substring(lastStartPos, lastEndPos+1));
                lastStartPos = lastEndPos + 1;
            }
            
            
        }
        return result;
    }

summary:1、如果要得到关于字符的缓冲区,采用endPosMap[S.charAt(i)-'a']=i这样的模式作缓冲区,这样既方便又直接

2、该题属于得到数量上的最值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值