LeetCode - 无重复字符的最长子串

Github: https://github.com/biezhihua/LeetCode/tree/master/src/com/bzh/leetcode

题目描述:
https://leetcodechina.com/problems/longest-substring-without-repeating-characters/description/

解题思路:
从题目中可以知晓:

  1. 需要能快速判断出是否遍历过相同的字符。
  2. 需要使用startIndexendIndex来表示当前的“无从重复子串“,for循环不适用于当前情况。
  3. 若当前字符是第一次遍历,则将其添加到集合中,并更新endIndex值。
  4. 若当前字符不是第一次遍历,需要更新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 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;
    }
}

你可能感兴趣的:(LeetCode,消灭LeetCode)