# Longest Substring Without Repeating Characters

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 static int lengthOfLongestSubstring(String s) {
if(s==null)
return 0;
s=s.trim();
int count=0;
Map<Character,Integer> map=new HashMap<Character,Integer>();
for(int i=0;i<s.length();i++){
if(!map.containsKey(s.charAt(i)))
map.put(s.charAt(i), i);
else{
count=Math.max(count, map.size());
i=map.get(s.charAt(i));
map.clear();
}
}
return Math.max(count, map.size());
}

public static int lengthOfLongestSubstring(String s){
if(s==null||s.length()<=0)
return 0;
boolean[] ch=new boolean[128];
int start = 0;
int count = 0;
for(int i=0;i<s.length();i++){
if(ch[s.charAt(i)]){//如果数组中不存在字符
count=Math.max(count, i-start);//比较子字符串长度和之前的长度记录
for (int k = start; k < i; k++) {
if (s.charAt(k)== s.charAt(i)) {
start = k + 1; //更新子字符串的起始位置
break;
}
ch[s.charAt(k)] = false;//将数组置为false
}
}else
ch[s.charAt(i)]=true;//将数组中字符对应的位置置为true
}
return Math.max(count, s.length()-start);
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：Longest Substring Without Repeating Characters 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)