# 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);
}

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

## 【LeetCode-面试算法经典-Java实现】【003-Longest Substring Without Repeating Characters（最长非重复子字符串）】

【003-Longest Substring Without Repeating Characters（最长非重复子字符串）】给定一个字符串，找字符中的最大非重复子串用start记录当前处理的开始位置...

## [LeetCode - 滑动窗口] 3. Longest Substring Without Repeating Characters

1 问题 Given a string, find the length of the longest substring without repeating characters. Exa...

## leetcode: Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, ...

## leetcode4 ---Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, ...

## (leetcode) Longest Substring Without Repeating Characters

Question : Given a string, find the length of the longest substring without repeating characters. ...

## LeetCode- 3. Longest Substring Without Repeating Characters

Description Given a string, find the length of the longest substring without repeating characters.E...

## leetcode_3 - Longest Substring Without Repeating Characters

leetcode_3 : Longest Substring Without Repeating Characters标签（空格分隔）： leetcode string twoPoints setGi...

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