3. Longest Substring Without Repeating Characters 最长子串,无重复字符

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

.
思路:知道要判断value > 1,但是答案的思路是:charAt(end)有重复就往前移,寻找下一个没有被重复的字母

counter是需要调节的,怎么调节需要动脑子。也不是一个一模一样的模板走天下:
counter表示的是无效的字母个数,但是因为之前统计过了,这里就一直减少。是为了维持两者在同一窗口内吧

d = Math.max(d, end - begin);
//d是在while循环之后更新,可能因为begin要尽量往前移,让结果尽量短?

 
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> map = new HashMap<>();
        int begin = 0, end = 0, counter = 0, d = 0;

        while (end < s.length()) {
            // > 0 means repeating character
            //if(map[s.charAt(end++)]-- > 0) counter++;
            char c = s.charAt(end);
            map.put(c, map.getOrDefault(c, 0) + 1);
            if(map.get(c) > 1) counter++;
            end++;
            
            while (counter > 0) {
                //if (map[s.charAt(begin++)]-- > 1) counter--;
                char charTemp = s.charAt(begin);
                if (map.get(charTemp) > 1) counter--;
                map.put(charTemp, map.get(charTemp)-1);
                begin++;

                //d = Math.max(d, end - begin);
            }
            //d = Math.max(d, end - begin);
            if (end - begin > d) 
                d = end - begin;
        }
        return d;
    }
}
View Code

 



posted @ 2020-07-31 11:19  苗妙苗  阅读(131)  评论(0编辑  收藏  举报