LeetCode:longest-substring-without-repeating-characters

题目描述:

Given a string, find the length of the longest substring without repeating characters. 
For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. 
For "bbbbb" the longest substring is "b", with the length of 1.

给定一个字符串,找到不重复的最长子字符串的长度。 例如,“abcabcbb”的不含重复字符的最长子字符串是“abc”,其长度为3.对于“bbbbb”,无重复字符的最长的子字符串是“b”,长度为1。

注意:子串是连续的。

题目解析:

"滑动窗口":例如abcabccc,

  • 当从左向右扫描到abca的时候,得把第一个a删掉得到bca,然后"窗口"继续向右滑动,
  • 每当加入一个新char的时候,左边部分检查有无重复的char,然后如果没有重复的就正常添加,有重复的话就左边扔掉一部分(从最左到重复char这段扔掉),
  • 在这个过程中记录最大窗口长度。
import java.util.HashMap;
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s == null || s.length() < 1) {
            return 0;
        }
        //HashMap<字符,下标>
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        int windowBegin = 0;
        int windowMax = 0;
        for(int i=0; i<s.length();i++){
            char  c = s.charAt(i);
            //窗口左边可能为下一个char,或者不变
            windowBegin = Math.max(windowBegin,(map.containsKey(c))? map.get(c)+1:0);
            windowMax = Math.max(windowMax, i-windowBegin+1);//当前窗口长度
            map.put(c,i);
        }
        return windowMax;
    }
}
发布了95 篇原创文章 · 获赞 16 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/tiankong_12345/article/details/90291054