当前位置:网站首页>leetcode:159.最多有两个不同字符的最长子串
leetcode:159.最多有两个不同字符的最长子串
2022-08-10 16:39:00 【OceanStar的学习笔记】
题目来源
题目描述
给定一个字符串 s ,找出 至多 包含两个不同字符的最长子串 t ,并返回该子串的长度。
示例 1:
输入: “eceba”
输出: 3
解释: t 是 “ece”,长度为3。
示例 2:
输入: “ccaabbb”
输出: 5
解释: t 是 “aabbb”,长度为5。
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
}
};
题目解析
思路
- 用一个map,key为字符,value为字符出现次数。
- 如果map的映射数量超过2个的时候,就删除一个映射
- 比如此时 HashMap 中e有2个,c有1个,此时把b也存入了 HashMap,那么就有三对映射了
- 这时 left 是0,先从e开始,映射值减1,此时e还有1个,不删除,left 自增1
- 这时 HashMap 里还有三对映射,此时 left 是1,那么到c了,映射值减1,此时e映射为0,将e从 HashMap 中删除,left 自增1
- 然后更新结果为 i - left + 1,以此类推直至遍历完整个字符串
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
int res = 0, left = 0;
unordered_map<char, int> m;
for (int i = 0; i < s.size(); ++i) {
++m[s[i]];
while (m.size() > 2) {
if (--m[s[left]] == 0) m.erase(s[left]);
++left;
}
res = max(res, i - left + 1);
}
return res;
}
};
思路
- 用一个map,key为字符,value为字符最新的坐标
- 比如题目中的例子 “eceba”,遇到第一个e,映射其坐标0,遇到c,映射其坐标1,遇到第二个e时,映射其坐标2,当遇到b时,映射其坐标3
- 如果map的映射数量超过2个的时候,就删除一个映射
- 从left开始往右找,看每个字符在map中的映射值是否等于当前left()
- 比如第一个e,HashMap 此时映射值为2,不等于 left 的0,那么 left 自增1,遇到c的时候,HashMap 中c的映射值是1,和此时的 left 相同,那么我们把c删掉,left 自增1,再更新结果
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
int res = 0, left = 0;
unordered_map<char, int> m;
for (int i = 0; i < s.size(); ++i) {
m[s[i]] = i;
while (m.size() > 2) {
if (m[s[left]] == left) m.erase(s[left]);
++left;
}
res = max(res, i - left + 1);
}
return res;
}
};
类似题目
边栏推荐
猜你喜欢
随机推荐
Could NOT find Doxygen (missing: DOXYGEN_EXECUTABLE)
Polling and the principle of webSocket and socket.io
【JDK】Oracle又一个JDK大版本停止扩展技术支持
华为-求int型正整数在内存中存储时1的个数
阿里工作7年,肝到P8就剩这份学习笔记了,已助朋友拿到10个Offer
leetcode:1137. 第 N 个泰波那契数
FTXUI基础笔记(botton按钮组件进阶)
promise笔记(三)
FTXUI基础笔记(botton按钮组件基础)
LeetCode-876. Middle of the Linked List
The sword refers to OfferⅡ 045. The bottommost leftmost value of the binary tree dfs
如何搭建知识库,让您的内容更丰富?
一文带你拿下信号卷积—常见信号卷积
被大厂面试官参考的Redis笔记,堪称Redis面试天花板
How to use bitwise operators in C language
Lua--table操作
FTXUI基础笔记(hello world)
本地导入不报错,服务器端报错 No module named xxx
64位 RT-Thread 移植到 Cortex-A53 系统 bug 修复笔记
【QT VS项目名称修改】









