题目:找出字符串中最长的子串。
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 Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null||s.length() == 0)
return 0;
HashMap<Character,Integer> map=new HashMap();
int max=0;
for(int i=0;i<s.length()-max;i++)//提高效率
{
int num=0;
for(int j=i;j<s.length();j++)
{
if(map.containsKey(s.charAt(j)) == false)
{
map.put(s.charAt(j),1);
num++;
if(num>max)
max=num;
}else
{
map=new HashMap();
break;
}
}
}
return max;
}
}
错误代码:
public int lengthOfLongestSubstring(String s) {
if(s == null||s.length() == 0)
return 0;
int max=0;
int num=0;
HashMap <Character,Integer> map=new HashMap();
for(int i=0;i<s.length();i++)
{
if(map.get(s.charAt(i)) == null)
{
map.put(s.charAt(i),1);
num++;
if(num>max)
{
max=num;
}
}
else
{
map=new HashMap();
map.put(s.charAt(i),1);
num=1;
}
}
return max;
}