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.
public class LongestSubstringWithoutRepeatingCharacters {
public int lengthOfLongestSubstring(String str) {
Set<Character> sets = new HashSet<Character>();
int max = 0;
int start=0;
for(int i=0,len=str.length();i<len;i++){
char cha = str.charAt(i);
if(sets.contains(cha)){
while(str.charAt(start)!=str.charAt(i)){
sets.remove(cha);
start++;
}
start++;
}else{
sets.add(cha);
}
max=i-start>max?i-start:max;
System.out.println(str.substring(start, i));
}
return max;
}
/**
* @param args
*/
public static void main(String[] args) {
LongestSubstringWithoutRepeatingCharacters l = new LongestSubstringWithoutRepeatingCharacters();
int len = l.lengthOfLongestSubstring("abcacddcefbb");
System.out.println(len);
}
}
使用集合Set不能包含重复元素的方法,从字符串的开始位置依次往后判断,如果存在重复元素,将子字符串的开始位置移动到重复元素位置再次判断。
3:Longest Substring Without Repeating Characters
原文:http://www.cnblogs.com/shisw/p/4367129.html