Github: https://github.com/biezhihua/LeetCode/tree/master/src/com/bzh/leetcode
题目描述:
https://leetcodechina.com/problems/longest-substring-without-repeating-characters/description/
解题思路:
从题目中可以知晓:
- 需要能快速判断出是否遍历过相同的字符。
- 需要使用
startIndex
和endIndex
来表示当前的“无从重复子串“,for
循环不适用于当前情况。 - 若当前字符是第一次遍历,则将其添加到集合中,并更新
endIndex
值。 - 若当前字符不是第一次遍历,需要更新
maxLength
,并移除startIndex
对应的数据,然后再更新startIndex
值。
最终代码:
/**
* https://leetcodechina.com/problems/longest-substring-without-repeating-characters/description/
*/
public class Code_3_4_LengthOfLongestSubstring {
@Test
public void test() {
Assert.assertEquals(3, lengthOfLongestSubstring("abcabcbb"));
Assert.assertEquals(1, lengthOfLongestSubstring("bbbbbb"));
Assert.assertEquals(3, lengthOfLongestSubstring("pwwkew"));
Assert.assertEquals(1, lengthOfLongestSubstring("p"));
Assert.assertEquals(0, lengthOfLongestSubstring(""));
Assert.assertEquals(9, lengthOfLongestSubstring("biezhqwua"));
Assert.assertEquals(2, lengthOfLongestSubstring("aab"));
Assert.assertEquals(3, lengthOfLongestSubstring("dvdf"));
Assert.assertEquals(5, lengthOfLongestSubstring("dveadf"));
}
public int lengthOfLongestSubstring(String s) {
int maxLength = 0;
if (s == null || s.length() == 0) {
return maxLength;
}
int startIndex = 0;
int endIndex = 0;
int length = s.length();
Set<Character> set = new HashSet<>();
while (startIndex < length && endIndex < length && startIndex <= endIndex) {
char c = s.charAt(endIndex);
if (!set.contains(c)) {
set.add(c);
endIndex++;
} else {
if (endIndex - startIndex > maxLength) {
maxLength = endIndex - startIndex;
}
set.remove(s.charAt(startIndex));
startIndex++;
}
}
if (endIndex - startIndex > maxLength) {
maxLength = endIndex - startIndex;
}
return maxLength;
}
}