字符串操作 —— 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;
    }
}
原文地址:https://www.cnblogs.com/s841844054/p/13736419.html