LeetCode 3.longest-substring-without-repeating-characters

Description:

Given a string, find the length of the longest substring without repeating characters.
查找最长的不重复子字符串
Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", 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

先放代码再看思路

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.length();
        int i=0,j=0;
        int maxLen = 0;
        bool exist[256] = {false};  //表示字符是否出现过,ascii有256个
        while(j<n){
            if(!exist[s[j]]){
                exist[s[j]] = true;
                j++;
            }else{
                maxLen = max(maxLen, j-i);
                while(s[i] != s[j]){
                    exist[s[i]] = false;
                    i++
                }
                i++;
                j++;
            }
        }
        return max(maxLen, j-i);
    }
};

思路:
exist[256]表示字符是否在substring里出现过。
i,j指向substring的开头和结尾,在i不变的情况下后移j,有两种可能:

  1. 如果s[j]未在substring里出现过,则exist[s[j]]=true,表示这个字符在substring里出现了,并且j后移一位。
  2. 如果s[j]在substring里出现过,则更新maxLen,且后移j和i,j一定是后移一位,没什么好说的。但是i的后移却需要考虑下:既然在这一段substring里有重复的字符,好比abcdec,此时把i后移到b处是毫无意义的,因为两个c还是会重复,因此至少要把i移到d处,这就解释了while(s[i] != s[j]){exist[s[i]] = false;i++}.

转载于:https://www.cnblogs.com/lepeCoder/p/7230540.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值