LEETCODE3---Longest Substring Without Repeating Characters

Given a string s, find the length of the longest substring without repeating characters.

Example 1:

Input: s = “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:

Input: s = “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:

Input: s = “pwwkew”
Output: 3
Explanation: The answer is “wke”, with the length of 3.
Notice that the answer must be a substring, “pwke” is a subsequence and not a substring.
Example 4:

Input: s = “”
Output: 0

Constraints:

0 <= s.length <= 5 * 104

思路:Example:

	  0 1 2 3 4 5
	  a b c d a b
      i                 j!<i,max=i-j+1=1;
      j

      a b c d a b
        i                s[i]!=s[j]
      j

      a b c d a b
        i               j!<i,i=1,p=0,max=i-p+1=2;
        j

      a b c d a b
          i                 s[i]!=s[j]
      j

      a b c d a b
          i               s[i]!=s[j]
        j

      a b c d a b
          i               j!<i,i=2,p=0,max=i-p+1=3;
          j

      a b c d a b
            i              s[i]!=s[j]
      j

      a b c d a b
            i                s[i]!=s[j]
        j

      a b c d a b
             i               s[i]!=s[j]
          j

      a b c d a b
            i                j!<i,i=3,p=0,max=i-p+1=4;
            j

      a b c d a b
              i               s[i]==s[j],i=4,p=j+1=1;break;max=i-p+1=4;
      j

      a b c d a b
                i               s[i]!=s[j]
      j
          
      a b c d a b
                i              s[i]==s[j],i=5,p=j+1=2;break;max=i-p+1=4;
        j

*/

#include <iostream>
using namespace std;

int lengthOfLongestSubstring(string s){
    int n=s.size(),i,j;
    int max=0;
    int p=0;
    for(i=0;i<n;i++){
        for(j=p;j<i;j++){
            if(s[i]==s[j]){     //当s[i]==s[j]时,则将从p下标再重新开始寻找
                p=j+1;
                break;
            }
        }
        if(i-p+1>max)max=i-p+1;     //最大子串长度
    }
    return max;
}
int main(){

    string s="abcbcdef";
    int f=lengthOfLongestSubstring(s);
    cout<<f;
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

365JHWZGo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值