leet_763_partirion_Labels(基于字符出现的频率切分字符串)

  • leet_code:链接
  • 问题描述:
    • 给定又一些小写字符组成的字符串,尽可能多的切分出子串,使得 每个字符在该子串中出现的次数最多,并依次返回各子串的长度。

    • 输入输出样例:

      • Input: S = “ababcbacadefegdehijhklij”
      • Output: [9,7,8]
      • 解析: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 .
      • 思路:First pass we record the last position for each letter. Second pass we keep the maximum position of the letters we have seen so far. If the pointer exceeds the maximum position, we found the part.
    • c++ 代码:

	class Solution
{
public:
	vector<int> partirionLabels(string S)
	{
		vector<int> res, pos(26, 0);
		for (auto i = 0; i < S.size(); ++i) pos[S[i] - 'a'] = i;
		for (auto i = 0, mark = INT_MIN, last_id = 0; i < S.size(); ++i)
		{
			mark = max(mark, pos[S[i] - 'a']);//note: must assign to argment 'mark'
			if (i == mark)
			{
				res.push_back(i - last_id + 1);
				last_id = i + 1;
			}
		}
		return res;
	}
};

c++主调函数

#include<iostream>
using namespace std;
#include<string>
#include<vector>
#include<algorithm>
int main(int args, char* argv[])
{
	string S = "ababcbacadefegdehijhklij";
	Solution solution;
	vector<int> res;
	res = solution.partirionLabels(S);
	for (int i : res)
		cout << i << endl;

	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值