Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: “pwwkew”
Output: 3
Explanation: The answer is “wke”, with the length of 3.
Note that the answer must be a substring, “pwke” is a subsequence and not a substring.
最长不重复公共子串的最大长度。
暴力法:三重循环,复杂度太高
优化一点:双指针+滑动窗口
两个指针i,j分别指向窗口两端,用一个set来记录划窗内的元素,当j遇到重复的元素时,i往右移,直到不含重复元素。判断是否为最长区间长度。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.empty()) return 0;
set<char> c;
int i=0,j=0,max_len=0;
while(j<s.size())
{
while(j<s.size() && c.count(s[j])==0)
{
c.insert(s[j]);
j++;
}
max_len = max(max_len,j-i);
while(s[i]!=s[j])
{
c.erase(s[i]);
i++;
}
if (i<s.size())
{
c.erase(s[i]);
i++;
}
}
max_len=max(max_len,j-i);
return max_len;
}
};
本文介绍了一种求解字符串中最长无重复字符子串的高效算法。通过使用双指针技术和滑动窗口的方法,避免了传统的三重循环所带来的高时间复杂度。文章详细解释了算法的具体实现过程,并给出了具体的代码示例。
961

被折叠的 条评论
为什么被折叠?



