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.
方法一 O(N^2)
public class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character,Integer> map=new HashMap<Character,Integer>();
int n=s.length();
int k=0;
int max=0;
for(int i=0;i<n;i++)
{
if(max>n-i)
break;
map.clear();
k=0;
for(int j=i;j<n;j++)
{
char c=s.charAt(j);
if(map.get(c)==null)
{
map.put(c,1);
k++;
}
else
{
break;
}
}
if(k>max)
max=k;
}
return max;
}
}
结果就是
方法二:O(N)
public class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character,Integer> map=new HashMap<Character,Integer>();
int n=s.length();
int start=0;
int max=0;
int i=0;
for(int j=0;j<n;j++)
{
char c=s.charAt(j);
if(map.get(c)==null)
{
map.put(c,j);
}
else
{
i=map.get(c);
if(start<=i)
start=i+1;
map.put(c,j);
}
if(max<(j-start+1))
max=j-start+1;
}
return max;
}
}