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数组ch[],存储256个字符最近一次出现的位置。首次出现某字符a时,其位置标记为ch[a],并用无重复字符计数器count记录无重复字符的长度,再在max更新其最大值。

当出现重复字符a时,从无重复字符计数器count减去两个重复字符之间的长度(ch[a]-start),并更新start为最后一个(任意)重复字符上一次出现的位置,然后更新重复字符的位置ch[a]

循环完整个字符串后,返回最大值max

举例说明:

"pwwkewk"
start = 0, count = 0, max = 0

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;
    }
}

linspiration
161 声望53 粉丝