3. Longest Substring Without Repeating Characters 3.最长的子字符串,不包含重复字符

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.

"abcabcbb"

j1 = 1
s.charAt(j) = b
字符串长度 = 2
j2 = 2
 
s.charAt(j) = c
字符串长度 = 3
j2 = 3
 
s.charAt(j) = a 这里应该不符合啊。i的没有初始化。其实i单独初始化也不行。必须i = 0, j = 0,j把i的路线全走一遍才行。这题太奇葩了。
这样一来也不叫所谓窗口了吧。
字符串长度 = 4 = 3 - 0 + 1 
j2 = 4
 
j1 = 2
j1 = 3
s.charAt(j) = a
字符串长度 = 4
j2 = 4
 
s.charAt(j) = b
字符串长度 = 4
j2 = 5
 
j1 = 4
j1 = 5
s.charAt(j) = c
字符串长度 = 4
j2 = 6
 
j1 = 6
s.charAt(j) = b
字符串长度 = 4
j2 = 7
 
j1 = 7
j1 = 8

反正有“窗口”的神韵在就行了,具体也是从i = 0, j = 0来开始实现的

一个字节只能表示256种符号,所以重复不重复要用int[256],好的

(j - i + 1);//注意字符串长度都得加1

map[s.charAt(i)] = 0;
//为啥要清零啊?因为之后统计的别的一连串字符串可以和之前的有重复,完全没问题。这是这一题的特殊之处

class Solution {
    public int lengthOfLongestSubstring(String s) {
        //cc
        if (s == null || s == "")
            return 0;
        
        int[] map = new int[256];
        int ans = 0;
        int i = 0;
        
        for (i = 0; i < s.length(); i++) {
            int j = i + 1;
            map[s.charAt(i)] = 1;
            System.out.println("j1 = " + j);
            
            while ((j < s.length()) && (map[s.charAt(j)] == 0)) {
                map[s.charAt(j)] = 1;
                ans = Math.max(ans, j - i + 1);
                System.out.println("s.charAt(j) = " + s.charAt(j));
                System.out.println("字符串长度 = " + ans);
                
                j++;
                System.out.println("j2 = " + j);
                
                System.out.println(" ");
            }
            //清空一下
            map[s.charAt(i)] = 0;
        }
        
        return ans;
    }
}
View Code

原文地址:https://www.cnblogs.com/immiao0319/p/13058425.html