请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zui-chang-bu-han-zhong-fu-zi-fu-de-zi-zi-fu-chuan-lcof
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.empty()) {
return 0;
}
int max = 0;
std::vector<char> temp_charlist;
for(int i =0;i<s.size();i++) {
vector<char>::iterator iter = std::find(temp_charlist.begin(),temp_charlist.end(),s[i]);
if(iter == temp_charlist.end()) {
temp_charlist.push_back(s[i]);
if(temp_charlist.size()>max) {
max = temp_charlist.size();
}
}else {
//包含三中情况,重复的元素在头上,在结尾,在中间,主旨是删除重复元素以及它之前的元素
temp_charlist.erase(temp_charlist.begin(),iter+1);
temp_charlist.push_back(s[i]);
if(temp_charlist.size()>max) {
max = temp_charlist.size();
}
}
}
return max;
}
};
int main()
{
Solution a;
int lll = a.lengthOfLongestSubstring("pwwkew");
cout << lll << endl;
return 0;
}```
## 需要注意的点(个人)
1.主循环中的第一个if里,要加max的时时更新,要不然如果无法进入else,到最后跑完了,max还是0
2.std::vector<int> iterator 的写法需要不借助IDE和百度写出来
3.algorithm 单词的写法,以及std::find 的用法。vector中用的是std::find而到map中或是unordered_map中直接引用find
5.temp子串在跟当前的元素进行比较时,如果有重复则,包含三中情况,重复的元素在头上,在结尾,在中间,主旨是删除重复元素以及它之前的元素
4.std::vector中的erase用法,注意最后一个参数,在删除的时候是会被保留的,所以一定要+1