早想做一下字符串的题,这个字符串题,自己感觉很经典,同样也是用了哈希表,把通常的O(n2),O(n3)变成了O(n)
Longest Substring Without Repeating Characters
Total Accepted: 52607 Total Submissions: 245781 My SubmissionsGiven 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.
Have you met this question in a real interview?
Yes
No
public class Longest_Substring_Without_Repeating_Characters {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int a =lengthOfLongestSubstring("adbcded");
System.out.println(a);
}
public static int lengthOfLongestSubstring(String s)
{ char[] arr = s.toCharArray();
int max=0;
int begin=0;
int end=0;
HashSet<Character> characters=new HashSet<Character>();
while(end<arr.length)
{
if(characters.contains(arr[end]))
{
while(begin<end&&arr[begin]!=arr[end])
{
characters.remove(arr[begin]);
begin++;
}
begin++;end++;
}
else
{
characters.add(arr[end]);
end++;
}
max = Math.max(max,end-begin);
}
return max;
}
}