OJ-leetcode-763. 划分字母区间(中等并查集)

目录

题目

思路

代码

结果

更优题解

提升笔记

全部代码


题目

字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。

示例 1:

输入:S = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。

提示:

    S的长度在[1, 500]之间。
    S只包含小写字母 'a' 到 'z' 。
链接:https://leetcode-cn.com/problems/partition-labels

思路

并查集

集合:字符的开始下标和结束下标

查找:字符开始到结束这个区间内的所有字符的集合中结束下标最大的

合并:查找时动态更新结束下标

由于按照顺序遍历,集合不需要保存开始下标,开始下标第一次为0,之后为结束下标+1即可。

代码

class Solution {
public:
	vector<int> partitionLabels(string S) {
		vector<int> res;
		//集合 记录字符对应的和终点
		unordered_map<char, int> um;
		int len = S.size();
		//初始化
		for (int i = 0; i < len; ++i)um[S[i]] = i;
		//查找与合并
		int start = 0;
		int end = 0;
		for (int j = 0; j < len; ++j)
		{
			end = max(end,um[S[j]]);
			if (j == end) {
				res.emplace_back(end - start + 1);
				start = end + 1;
			}
			//cout << start << " " << end << endl;
		}
		return res;
	}
};

结果

结果截图

更优题解

思路差不多,粘贴个官方吧-贪心算法+双指针

并查集

提升笔记

给定了小写26个字母,可以使用数组而不是unordered_map来进行存储。数组是真的O(1),但是unordered_map里面其实还有一些浪费时间的东西,比如计算hash值。

全部代码

/*
https://leetcode-cn.com/problems/partition-labels/
Project: 763. 划分字母区间
Date:    2020/10/22
Author:  Frank Yu
*/
#include<vector>
#include<algorithm>
#include<iostream>
#include<unordered_map>
using namespace std;
void check(vector<int> res)
{
	for (auto i : res)
	{
		cout << i << " ";
	}
	cout << endl;
}
class Solution {
public:
	vector<int> partitionLabels(string S) {
		vector<int> res;
		//集合 记录字符对应的和终点
		unordered_map<char, int> um;
		int len = S.size();
		//初始化
		for (int i = 0; i < len; ++i)um[S[i]] = i;
		//查找与合并
		int start = 0;
		int end = 0;
		for (int j = 0; j < len; ++j)
		{
			end = max(end,um[S[j]]);
			if (j == end) {
				res.emplace_back(end - start + 1);
				start = end + 1;
			}
			cout << start << " " << end << endl;
		}
		return res;
	}
};

//主函数
int main()
{
	Solution s;
	check(s.partitionLabels("ababcbacadefegdehijhklij"));
	//check(s.partitionLabels(""));
	//check(s.partitionLabels("abc"));
	//check(s.partitionLabels("awddwetwedwesfgrhthy"));
	return 0;
}

更多内容:OJ网站题目分类,分难度整理笔记(leetcode、牛客网)

喜欢本文的请动动小手点个赞,收藏一下,有问题请下方评论,转载请注明出处,并附有原文链接,谢谢!如有侵权,请及时联系。如果您感觉有所收获,自愿打赏,可选择支付宝18833895206(小于),您的支持是我不断更新的动力。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lady_killer9

感谢您的打赏,我会加倍努力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值