题目:
从一个字符串中找到一个连续子串,该子串中任何两个字符不能相同,求子串的最大长度并输出一条最长不重复子串。
思路:
利用map表hashtable[256]来保存出现过的字符,然后从头开始遍历字符串,
1、如果当前字符ch已经出现过(hashtable[ch]==1),则表示一个局部最长不重复子串已经出现:
此时更新子串长度,同时更新最长子串的起始位置start。
同时将start到重复字符ch之间的map表重置为0(表示没有出现过)然后从ch的下个字符作为新的子串的开始;
2、如果当前字符ch没有出现过:
则设置hashTable为1(表示出现过)。
时间复杂度:
O(n)
class Solution {
public:
/**
*
* @param s string字符串
* @return int整型
*/
int lengthOfLongestSubstring(string s) {
// write code here
//https://www.cnblogs.com/AndyJee/p/4875508.html 原理
//双指针+哈希法
vector<unsigned char> hashtable(256,0);
int len = s.size();
int start = 0;
int res = 0;
auto i = start;
for(;i<len;i++)
{
//重复
if(hashtable[s[i]] == 1)
{
//更新信息 长度
if(res<i-start) //注意此时的s[i]是已经重复了,所以当前的未重复子串长度是 i- start;
{
res = i-start;
}
while(s[start]!=s[i]) //开始更新start
{
hashtable[s[start]] = 0;
start++;
}
start++;//从下一个开始
}else
{
hashtable[s[i]]++;
}
}
res = res<i-start?i-start:res;
return res;
}
};