# 【LeetCode】3 Longest Substring Without Repeating Characters

220人阅读 评论(0)

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;
}
}
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：30942次
• 积分：1080
• 等级：
• 排名：千里之外
• 原创：75篇
• 转载：11篇
• 译文：2篇
• 评论：4条
文章分类