• LC 763. 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.

    Runtime: 8 ms, faster than 43.40% of C++ online submissions for Partition Labels.

    第一次实现用的是map,第二次实现用的是数组,差了一倍的运行速度。

    #include <vector>
    #include <string>
    #include <unordered_map>
    #include <map>
    #include <iostream>
    using namespace std;
    
    class Solution {
    public:
      vector<int> partitionLabels(string S) {
        int map[256];
        for(int i=0; i<S.size(); i++){
          map[(int)S[i]] = i;
        }
        int idx = 0;
        vector<int> ret;
        while(idx < S.size()){
          int tmpidx = idx;
          int maxback = map[(int)S[tmpidx]]+1;
          while(tmpidx < S.size() && tmpidx < maxback){
            maxback = max(maxback, map[(int)S[tmpidx]]+1);
            tmpidx++;
          }
          ret.push_back(maxback - idx);
          idx = maxback;
        }
        return ret;
      }
    };
  • 相关阅读:
    D-Power Products
    B2
    软考知识点梳理--螺旋模型
    软考知识点梳理--敏捷方法
    软考知识点梳理--瀑布模型
    软考知识点梳理--统一软件开发过程RUP
    软考知识点梳理--信息系统生命周期
    软考知识点梳理--信息资源管理
    软考知识点梳理--以太网
    软考知识点梳理--应急储备与管理储备
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10188343.html
Copyright © 2020-2023  润新知