# 【LeetCode】3 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.

Solution1

public class Solution {
public int lengthOfLongestSubstring(String s) {
boolean []exist = new boolean[256];
int i=0,maxLen = 0;
for(int j=0;j<s.length();j++)
{
while(exist[s.charAt(j)])
{
exist[s.charAt(i)] = false;
i++;
}
exist[s.charAt(j)]=true;
maxLen = Math.max(j-i+1, maxLen);
System.out.println();
}
return maxLen;
}
}

Solution2 HashMap

public class Solution {
public int lengthOfLongestSubstring(String s) {
int maxLen = 0;
int availableFrom = 0;
Map<Character,Integer> map = new HashMap<Character,Integer>();
for(int j=0;j<s.length();j++)
{
if(map.containsKey(s.charAt(j)))
{
int last = map.get(s.charAt(j));
availableFrom = Math.max(availableFrom, last+1);
}
maxLen = Math.max(maxLen, j-availableFrom+1);
map.put(s.charAt(j), j);
}
return maxLen;
}
}
• 本文已收录于以下专栏：

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