题目
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
思路
用string temp保存遍历过程中逐渐累加的不重复子串,遍历原字符串,判断当前字符是否在temp中,没有就加,有的话就找到这个字符在temp中index,那么从index+1开始,temp中后面的字符肯定与当前遍历的字符不重复,所以两者相加,形成新的temp。每次判断temp的长度,进行更新res即可。
感觉我得算法不慢啊,只超过了40%,然后拿官方的滑动窗口代码测试一下,结果竟然差不多🙄🙄🙄
AC代码
#include <iostream>
#include <string>
using namespace std;
class Solution
{
public:
int lengthOfLongestSubstring(string s)
{
if (s == "")
return 0;
int res = 0;
string temp = "";
for (int i = 0; i < s.size(); i++)
{
int index = temp.find(s[i]);
if (index == string::npos) //不在temp中
{
temp += s[i];
if (temp.size() > res)
//这里进行判断位置也可以放在if外面,但都无所谓,因为发现相同后,新的temp长度不会大于当前的
res = temp.size();
}
else
{//例如abca,当发现第二个a之前出现了,所以temp需要重新取成bc加上a;
//不用担心当前s[i]为最后,因为为最后也不能让temp变成最大长度
temp = temp.substr(index+1) + s[i];
}
}
return res;
}
};
int main()
{
Solution so;
string s;
cin >> s;
cout << so.lengthOfLongestSubstring(s) << endl;
return 0;
}
总结
- 不重复的字符,可以使用散列表
- 子串,可以想到滑动窗口的思想,
虽然我的解法本质差不多吧?