题目描述
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.
解题思路
这道题的关键是维护一个窗口,具体解释可参考这篇文章:
http://www.aichengxu.com/view/11060
public class Solution {
public int lengthOfLongestSubstring(String s) {
if(null == s || 0 == s.length())
{
return 0;
}
Set<Character> windows = new HashSet<Character>();
int max = 1;
int left = 0;
int right = 0;
while(right <= s.length() - 1)
{
if(windows.contains(s.charAt(right)))
{
while(s.charAt(right) != s.charAt(left))
{
windows.remove(s.charAt(left));
++left;
}
++left;
}
else
{
windows.add(s.charAt(right));
max = max > (right - left + 1)? max : (right - left + 1);
}
++right;
}
return max;
}
}
本文介绍了一种求解字符串中最长无重复字符子串长度的高效算法,并提供了详细的实现思路及Java代码示例。

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



