题目
给定一个字符串,请你找出其中不含有重复字符的最长子串的长度
示例1
输入:s = "abcabcbb"
输出:3
示例2
输入:s = "bbbbb"
输出:1
示例3
输入:s = ""
输出:0
思路
对于给定字符串s,求解目标无重复字符最长子串的每一个字符,都服从在给定字符串s中的出现顺序。因此我们可以分别借助头指针head与尾指针tail在给定的字符串中进行滑移比较,即先确定head的位置,再进行tail的移动,当head与tail相等时,更新head的位置,形成滑动窗口。
细节上,我们可以借助hashtable来判断重复字符,或者更直接的进行head与tail的相等比较。
题解
1.依靠hashtable的解法。
class Solution{
public:
int lengthoflongesSubstring(string s){
std::unordered_set<char> sets; //create a hash set
int n = s.size(); //length of string s
int rp = -1, ans = 0; //init the right pointer
for(int i = 0; i < n; ++i) //set the left pointer
{
if(i != 0)
sets.erase(s[i - 1]); //outer loop, erase the same char
while(rp + 1 < n && !sets.count(s[rp + 1]))
{
sets.insert(s[rp + 1]); //insert the different char from head
++rp;
}
ans = max(ans, rp - i + 1); //record the maximum ans as the result
}
return ans;
}
}
2.更快的直接比较方式
class Solution{
public lengthOfLongestSubstring(string s){
int head = 0, tail = 0, ans = 0;
while(tail < s.size())
{
for(int i = head; i < tail; ++i)
{
if(s[i] == s[tail]) //if head == tail, increase the head
{
head = i + 1;
break; //and jumping out the loop, increasing tail
}
}
++tail; //the tail increased
if((tail - head) > ans) //thus, (tail - head) as ans
ans = tail - head;
}
return ans;
}
}
blooming most splendid self.