Longest Substring Without Repeating Characters - LeetCode

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.
解析:找出给定字符串中无重复子串的最大长度。解法是采用一种“滑动窗口”的策略,比如给定一字符串"abcda",那么我可以先扫描一遍,扫描过的字符可以通过建立哈希表来记录其下标,每次扫描都查询一下当前字符是否出现在已扫描过的字符当中,即查找key(字符)所对应的value(下标)是否存在,若存在,则更新“窗口左边界”(方便计算子串长度)和字符对应下标再继续扫描,每次扫描都更新一遍最大长度。例如在找到了无重复子串"abcd"后,当我继续扫描时,发现字符"a"重复了,那么我可以将原来的"a"丢弃,添加新的"a"以更新扫描子串(即更新“窗口左边界”和字符对应下标),这样再以"bcda"的形式继续扫描,以此类推…。
解法:①C++

int lengthOfLongestSubstring(string s) {
      int len=s.length(),maxlen=0,bound=0; //bound为“窗口左边界”
      map<char,int> mp;
      for(int i=0;i<len;i++){
        if(mp.find(s[i])!=mp.end()) bound=max(bound,mp[s[i]]+1); //更新窗口边界
        maxlen=max(maxlen,i-bound+1); //更新子串最大长度
        mp[s[i]]=i;
      }
      return maxlen;
    }

//另一种写法:

int lengthOfLongestSubstring(string s) {
      int len=s.length(),maxlen=0,curPos=-1;
      map<char,int> pos; //记录字符对应下标
      for(int i=0;i<len;i++) pos[s[i]]=-1;
      for(int i=0;i<len;i++){
      //若无出现重复字符,则子串长度i-curPos的结果就是不断+1,当字符重复时,
      //curPos为字符最新出现的地方
        curPos=max(curPos,pos[s[i]]); 
        maxlen=max(maxlen,i-curPos); //更新长度
        pos[s[i]]=i; //更新下标
      }
      return maxlen;
    }

②Java

import java.util.HashMap;
class Solution {
    public int lengthOfLongestSubstring(String s) {
      int len=s.length(),maxlen=0,bound=0;
      HashMap<Character,Integer> pos=new HashMap<>();
      for(int i=0;i<len;i++){
        char ch=s.charAt(i);
        if(pos.containsKey(ch)) bound=Math.max(bound,pos.get(ch)+1); //更新“窗口左边界”
        maxlen=Math.max(maxlen,i-bound+1); //更新长度
        pos.put(ch,i);
      }
      return maxlen;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值