3. Longest Substring Without Repeating Characters最长不重复子串

Longest Substring Without Repeating Characters
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.

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s.length() == 0)
            return 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max = 0;
        //i遍历字符串,j记录所求串的first字符
        for (int i = 0, j = 0; i < s.length(); ++i) {
            if (map.containsKey(s.charAt(i))) {
// 为保证j有效前提,取j和当前字符在map中的重复位置的最右值: 继续寻找
                j = Math.max(j, map.get(s.charAt(i)) + 1);
            }
            map.put(s.charAt(i), i);
            max = Math.max(max, i - j + 1);//每次循环后,更新max值
        }
        return max;
    }
}

不理解 j = Math.max(j, map.get(s.charAt(i)) + 1); 时,可以参考下面:

The variable “j” is used to indicate the index of first character of this substring. If the repeated character’s index is less than j itself, which means the repeated character in the hash map is no longer available this time

例如:“abcba”
j:不重复子串的first
i:不重复子串的end;

当i=3,时,判断map中已有b,则j=原有值的索引(1)+1=2;(所求串中b不重复,最多从索引2开始)
当i=4,时,判断map中已有a,此时若直接将所求不重复子串的初始位置j=原有值的索引(0)+1=1,则会出现,之前所求的重复b矛盾失效;
因此,在赋值所求不重复子串的初始位置j时,需要考虑到所有字符的不重复的最大值;

你可能感兴趣的:(leetcde)