3. Longest Substring Without Repeating Characters

本文深入探讨了寻找字符串中最长无重复字符子串的算法实现,通过三种不同的方法进行讲解:暴力查找、使用isunique函数判断和滑动窗口技巧。每种方法都提供了详细的代码示例,帮助读者理解其工作原理及效率分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

附上后两种方法的参考链接

3. Longest Substring Without Repeating Characters

Medium

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.

Accepted

1,143,449

Submissions

3,944,388

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n=s.length();
        string max="";
        string tmp="";
        string tmp1="";
        string m=s;
        for(int k=0;k<n;k++){//暴力查找,后面想到好方法再更新
            s=m.substr(k);
            //cout<<s<<endl;
            for(int i=0;i<s.length();i++){
                int flag=0;
                for(int j=0;j<tmp.length();j++){
                    if(tmp[j]==s[i]){flag=1;break;}
                }
                if(flag==0) 
                {
                    tmp1+=s[i];
                    tmp=tmp1;
                }else{
                    tmp=tmp1="";
                    break;
                }
                if(max.length()<tmp1.length()){
                    max=tmp1;
                }
            }
        }
        //cout<<max<<endl;
        return max.length();
    }
};

下面这个看了别人的题解用的是一个isunique函数,但是貌似超时了?

class Solution {
public:
    bool isunique(string s,int start,int end){
        set<char> st;
        for(int i=start;i<end;i++){
            if(st.find(s[i])!=st.end()) return false;
            st.insert(s[i]);
        }
        return true;
    }
    int lengthOfLongestSubstring(string s) {
        int MAX=0;
        for(int i=0;i<s.length();i++){
            for(int j=i+1;j<=s.length();j++){
                if(isunique(s,i,j)){
                    MAX=max(MAX,j-i);
                }
            }
        }
        return MAX;
    }
};

下面这个用的是滑动窗口:(好像也没有比第一个暴力快多少,时间复杂度应该是O(N^2))

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n=s.length();
        set<char> st;
        int i=0,j=0,ans=0;
        while(i<n&&j<n){
            if(st.find(s[j])==st.end()){//无重复则尾巴右移
                st.insert(s[j]);j++;
                ans=max(ans,j-i);
            }else{//有重复则头右移
                st.erase(s[i]);
                i++;
            }
        }
        return ans;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值