Leetcode 763. Partition Labels

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/83546443

文章作者: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/

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试