经典问题,最长连续子串,DP解决
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.
package l3;
/*
* DP考虑的是到当前就没有数据的情况
* 后面的结果依赖于前面的结果
*/
public class Solution {
public int lengthOfLongestSubstring(String s) {
if(s.equals("")) return 0;
char[] cs = s.toCharArray();
int start = 0, end = 0;
int []nearest_pos = new int[256];
boolean []exist = new boolean[256];
int max = 1;
for(int i=0; i<cs.length; i++) {
if(! exist[cs[i]]) {
end = i;
exist[cs[i]] = true;
nearest_pos[cs[i]] = i;
if(end - start + 1 > max) max = end - start + 1;
} else {
for(int j=start; j<nearest_pos[cs[i]]; j++) exist[cs[j]] = false;
start = nearest_pos[cs[i]] + 1;
nearest_pos[cs[i]] = i;
end = i;
}
}
return max;
}
}