贪心算法--划分字母区间

#include<iostream>
#include<stack>
#include <vector>
#include<string>
#include<algorithm>
#include<unordered_map>
#include <climits>
#include<queue>
#include<unordered_set>
#include<cctype>
#include <sstream>
#include<set>
using namespace std;
#define maxsize 100
//划分字母区间:
//给定一个只包含小写字母的字符串 S,将字符串 S 划分为尽可能多的部分,
// 使得每个字母最多只出现在一个部分中,并返回每个部分的长度。
// 例如,给定字符串 S = "ababcbacadefegdehijhklij",
// 划分后的部分为["ababcbaca", "defegde", "hijhklij"]。
vector<int> partitionLabels(string s) {
    vector<int> partitions;
    unordered_map<char, int> lastIndex; // 记录每个字符最后出现的位置
    for (int i = 0; i < s.size(); ++i) {
        lastIndex[s[i]] = i;
    }

    int start = 0;
    int end = 0;
    for (int i = 0; i < s.size(); ++i) {
        end = max(end, lastIndex[s[i]]); // 更新当前划分范围的结束位置
        if (i == end) { // 如果当前位置是当前划分范围的结束位置
            partitions.push_back(end - start + 1); // 添加当前划分范围的长度到结果中
            start = end + 1; // 更新下一个划分范围的起始位置
        }
    }

    return partitions;
}

int main() {
    string s = "ababcbacadefegdehijhklij";
    vector<int> result = partitionLabels(s);
    cout << "划分后的部分长度为:";
    for (int len : result) {
        cout << " " << len;
    }
    cout << endl;
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值