zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    适合高要求应用的高性能MEMS IMU解决方案
    apt-get本地软件源搭建
    DNS与ARP协议
    vue computed
    常见宏任务与微任务
    Promise.resolve解析
    为什么var可以重复声明
    symbol
    引用类型转换为原始值(基本类型)
    ==运算符
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13856191.html
Copyright © 2011-2022 走看看