题目:
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.
这道题看起来和数据结构于算法分析上的最大子序和很像,应该就是一种东西。求解方法如下:
class Solution {
public int lengthOfLongestSubstring(String s) {
char[] array = s.toCharArray();
int[] exist = new int[200];
Arrays.fill(exist, -1);
int current = 0;
int max = 0;
int head = 0;
for (int i = 0; i < array.length; i++) {
int pos = array[i];
if (exist[pos] == -1) {
exist[pos] = i;
current++;
} else {
if (exist[pos] > head)
head = exist[pos];
current = i - head;
exist[pos] = i;
}
if (current > max) {
max = current;
}
}
return max;
}
}