LeetCode 763 划分字母区间

LeetCode 763 划分字母区间

问题描述:
字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。

双指针

  • 指针curr指向当前遍历到的字符
  • 指针end指向已遍历过的字符最后出现的位置
  • 使用一个数组统计每个字符在字符串S中最后出现的位置

执行用时:5 ms, 在所有 Java 提交中击败了73.08%的用户
内存消耗:36.9 MB, 在所有 Java 提交中击败了97.69%的用户

class Solution {
    public List<Integer> partitionLabels(String s) {
        List<Integer> ans = new ArrayList<>();
        if(s==null || s.length()==0) {
            return ans;
        }
        //统计每个字符的最后出现位置
        int[] lastIdx = new int[26];
        for(int i=0; i<s.length(); i++) {
            lastIdx[s.charAt(i)-'a'] = i;
        }
        //双指针
        int curr = 0, end = lastIdx[s.charAt(curr)-'a'], lastEnd = curr-1;
        while(curr < s.length()) {
            //找到一个分段
            if(curr==end) {
                // System.out.println("lastEnd="+lastEnd+"  end="+end);
                ans.add(end-lastEnd);
                lastEnd = curr;
            }
            curr++;
            if(curr<s.length()) {
                end = Math.max(end, lastIdx[s.charAt(curr)-'a']);
            }
        }

        return ans;
    }
}
原文地址:https://www.cnblogs.com/CodeSPA/p/13856191.html