美文网首页Leetcode
Leetcode 763. Partition Labels

Leetcode 763. Partition Labels

作者: SnailTyan | 来源:发表于2018-10-30 18:16 被阅读0次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Partition Labels

    2. Solution

    • Version 1
    class Solution {
    public:
        vector<int> partitionLabels(string S) {
            unordered_map<char, int> m;
            vector<int> result;
            vector<int> indices(S.length());
            for(int i = 0; i < S.length(); i++) {
                m[S[i]] = i;
            }
            for(int i = 0; i < S.length(); i++) {
                indices[i] = m[S[i]];
            }
            int max = 0;
            int start = 0;
            for(int i = 0; i < S.length(); i++) {
                if(indices[i] > max) {
                    max = indices[i];
                }
                if(i == max) {
                    result.push_back(max - start + 1);
                    start = i + 1;
                    max = 0;
                }
            }
            return result;
        }
    };
    
    • Version 2
    class Solution {
    public:
        vector<int> partitionLabels(string S) {
            unordered_map<char, int> m;
            vector<int> result;
            for(int i = 0; i < S.length(); i++) {
                m[S[i]] = i;
            }
            int max = 0;
            int start = 0;
            for(int i = 0; i < S.length(); i++) {
                if(m[S[i]] > max) {
                    max = m[S[i]];
                }
                if(i == max) {
                    result.push_back(max - start + 1);
                    start = i + 1;
                    max = 0;
                }
            }
            return result;
        }
    };
    

    Reference

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

    相关文章

      网友评论

        本文标题:Leetcode 763. Partition Labels

        本文链接:https://www.haomeiwen.com/subject/qxlgtqtx.html