题目:找出字符串中最长的子串。
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;
}
本文介绍了一种求解字符串中最大长度不重复字符子串的算法实现,通过使用哈希映射记录字符出现的位置来避免重复,并提供了一个示例代码,展示了如何有效地更新最大子串长度。
5733

被折叠的 条评论
为什么被折叠?



