[LeetCode] Longest Substring Without Repeating Characters

NO IMAGE

Problem

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.

Note

建立int

i = 0:

a = 'p'
ch['p'] = 0   1 = 1
count = 1
max = 1

i = 1:

a = 'w'
ch['w'] = i   1 = 2
count = 2
max = 2

i = 2:

a = 'w'
ch['w'] = 2 > start = 0
count = count - (ch['w'] - start) = 2 - (2 - 0) = 0
start = 2
ch['w'] = 2   1 = 3
count = 1
max = 2

i = 3:

a = 'k'
ch['k'] = 3   1 = 4
count = 2
max = 2

i = 4:

a = 'e'
ch['e'] = 5
count = 3
max = 3

i = 5:

a = 'w'
ch['w'] = 3 > start = 2
count = count - (ch['w'] - start) = 3 - (3 - 2) = 2
start = 3
ch['w'] = 6
count = 2   1 = 3
max = 3

i = 6:

a = 'k'
ch['k'] = 4
start = 3
count = count - (ch['k'] - start) = 3 - (4 - 3) = 2
start = 4
ch['k'] = 7
count = 3
max = 3

Solution

public class Solution {
public int lengthOfLongestSubstring(String s) {
int[] ch = new int[256];
int max = 0, count = 0, start = 0;
for (int i = 0; i < s.length(); i  ) {
char a = s.charAt(i);
if (ch[a] > start) {
count -= ch[a] - start;
start = ch[a];
}
ch[a] = i 1;
max = Math.max(max,   count);
}
return max;
}
}