leetcode 763-划分字母区间

题目: https://leetcode.cn/problems/partition-labels/
本例使用题解中的贪心算法。并加了一些注释。
程序结构如下,
划分字母区间代码结构
CMakeLists.txt

cmake_minimum_required(VERSION 2.6)

project(partition_labels)
set(CMAKE_CXX_STANDARD 20)
add_definitions(-g)

string(REPLACE ".cpp" "" file "main.cpp")
add_executable(${file}  "main.cpp")

main.cpp

#include <iostream>
#include <vector>
#include <algorithm>
#include <array>

using namespace std;

class Solution {
public:
    vector<int> partitionLabels(string s) {
        array<int, 26> last;
        // 记录所有字符最后出现的位置
        for(int i=0; i<s.size(); ++i) {
            last[s[i] - 'a'] = i;
        }
        vector<int> partition;
        int start = 0;
        int end = 0;
        for(int i=0; i<s.size(); ++i) {
            end = max(end, last[s[i]-'a']);
            // 出现一个最大match
            if(end == i) {
                // 保存最大match长度用于输出
                partition.emplace_back(end-start+1);
                // 接着寻找下一个子串的最大值
                start = end + 1;
            }
        }
        return partition;
    }
};

auto main(int argc, char** argv) -> int {
    Solution s;
    string str = "ababcbacadefegdehijhklij";
    auto partition = s.partitionLabels(str);
    cout << str << " can be paritioned to the below parts: ";
    for_each(partition.begin(), partition.end(), [](int const ele) {
        cout << ele << " ";
    });

    cout << "\n";
    return EXIT_SUCCESS;
}

程序输出如下,
Partition Labels输出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值