Longest Substring Without Repeating Characters

本文介绍了一种求解字符串中最长无重复字符子串的高效算法。通过使用双指针技术和滑动窗口的方法,避免了传统的三重循环所带来的高时间复杂度。文章详细解释了算法的具体实现过程,并给出了具体的代码示例。

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;
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值