LeetCode--Partition Labels

思路:

    1.首先将数组中字母的最大索引设成映射.

    2.然后从头遍历数组,先截取到字母最大索引处,查看截取的字符串中是否存在比最大索引更大的字母索引

    3.如果存在则将新的截取的字符串进行查看,直到字母的最大索引和内部的所有最大索引都重合

    4.添加个数到List

class Solution {
    public List<Integer> partitionLabels(String S) {
        List<Integer> res=new ArrayList<Integer>();
        Map<Character,Integer> map=new HashMap<Character,Integer>();
        for(int i=0;i<S.length();i++){
            map.put(S.charAt(i),i);
        }
        for(int i=0;i<S.length();i++){
            char c=S.charAt(i);
            int last_pos=map.get(c);
            String sub=S.substring(i,last_pos+1);
            int max_pos=max_pos(sub,map);
            while(max_pos>last_pos){
                sub=S.substring(i,max_pos+1);
                last_pos=max_pos;
                max_pos=max_pos(sub,map);
            }
            res.add(max_pos-i+1);
            i=max_pos;
        }

        return res;
    }

    private int max_pos(String sub,Map<Character,Integer> map){
        int max_pos=0;
        for(int i=0;i<sub.length();i++){
            if(map.get(sub.charAt(i))>max_pos){
                max_pos=map.get(sub.charAt(i));
            }
        }

        return max_pos;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_21752135/article/details/80038877