zoukankan      html  css  js  c++  java
  • 字符串操作 —— 763_划分字母区间

    3. 763_划分字母区间
    /*
    输入:S = "ababcbacadefegdehijhklij"
    输出:[9,7,8]
    解释:
    划分结果为 "ababcbaca", "defegde", "hijhklij"。
    每个字母最多出现在一个片段中。
    像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。
    */
    
    /**
     *方法一,不用额外的空间,利用Stirng的方法
     */
    class Solution {
        public List<Integer> partitionLabels(String S) {
            List<Integer> res = new ArrayList<>();
            if(S == null || S.length() == 0) return res;
            int i = 0;
            while(i < S.length()){
                int left = i;
                int right = S.lastIndexOf(S.charAt(i));
                while(i < right){
                    i++;
                    if(S.lastIndexOf(S.charAt(i)) > right)
                        right = S.lastIndexOf(S.charAt(i));
                }
                res.add(right - left + 1);
                i = right+1;
            }
            return res;
        }
    }
    
    /**
     * 方法二,贪心,先存储每个字母最后出现的位置,最后遍历一次 o(n),O(n)
     */
    public class Solution {
        public List<Integer> partitionLabels(String S) {
            int[] last = new int[26];
            for (int i = 0; i < S.length(); ++i) {
                last[S.charAt(i) - 'a'] = i;
            }
            int j = 0, anchor = 0;
            List<Integer> ans = new ArrayList<>();
            for (int i = 0; i < S.length(); ++i) {
                j = Math.max(j, last[S.charAt(i) - 'a']);
                if (i == j) {
                    ans.add(i - anchor + 1);
                    anchor = i + 1;
                }
            }
            return ans;
        }
    }
    
  • 相关阅读:
    JavaScript -- BATweb笔试面试
    1--html属性
    0--node安装
    1-- express
    lsof命令
    1--字符串和数组的指向问题
    19--复杂链表的复制。
    18--二叉树中和为某一值的路径
    剑指offer——64和为s的数字
    剑指offer——04二维数组中的查找
  • 原文地址:https://www.cnblogs.com/s841844054/p/13736419.html
Copyright © 2011-2022 走看看