zoukankan      html  css  js  c++  java
  • #Leetcode# 763. Partition Labels

    https://leetcode.com/problems/partition-labels/

    A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.

    Example 1:

    Input: S = "ababcbacadefegdehijhklij"
    Output: [9,7,8]
    Explanation:
    The partition is "ababcbaca", "defegde", "hijhklij".
    This is a partition so that each letter appears in at most one part.
    A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
    

    Note:

    1. S will have length in range [1, 500].
    2. S will consist of lowercase letters ('a' to 'z') only.

    代码:

    class Solution {
    public:
        vector<int> partitionLabels(string S) {
            vector<int> ans;
            int len = S.length();
            map<char, int> mp;
            for(int i = 0; i < len; i ++) 
                mp[S[i]] = i;
            int st = 0, maxx = 0;
            for(int i = 0; i < len; i ++) {
                maxx = max(maxx, mp[S[i]]);
                if(i == maxx) {
                    ans.push_back(i - st + 1);
                    st = i + 1;
                }
            }
            return ans;
        }
    };
    

      

    代码(JAVA):

    class Solution {
        public List<Integer> partitionLabels(String S) {
            int n = S.length();
            List<Integer> ans = new ArrayList<Integer>();
            
            int st = 0, maxx = 0;
            for(int i = 0; i < n; i ++) {
                maxx = Math.max(maxx, S.lastIndexOf(S.charAt(i)));
                if(maxx == i) {
                    int t = i - st + 1;
                    ans.add(t);
                    st = i + 1;
                }
            }
            return ans;
        }
    }
    

      

  • 相关阅读:
    对话系统综述
    3.738. 单调递增的数字
    3.765-情侣牵手
    2.135-分发糖果
    1.312-戳气球
    4.BN推导
    3.CNN-卷积神经网络推导
    2.DNN-神经网络推导
    联系人
    DS博客作业05--查找
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10848667.html
Copyright © 2011-2022 走看看