Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
1、将时间复杂度降低到O(n),牺牲空间
int[] address = new int[256]; //存储每个字符在该字符串中出现的位置,并赋初值“-1”
for(int i=0;i<256;i++)
address[i]=-1;
2、方法如下:
public static int lengthOfLongestSubstring(String s) {
int[] address = new int[256];
for(int i=0;i<256;i++)
address[i]=-1;
int index = -1;
int sum = 0;
for(int i=0;i<s.length();i++){
if(address[s.charAt(i)]>index){
index=address[s.charAt(i)];
}
if(i-index>sum)
sum=i-index;
address[s.charAt(i)]=i;
}
return sum;
}