Longest Substring Without Repeating Characters

link:https://leetcode.com/problems/longest-substring-without-repeating-characters/
public class LongestSubstringWithoutRepeatingCharacters {
    /**
     * Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length
     * of 3.
     * 
     * @param s
     * @return
     */
    public static int lengthOfLongestSubstring(String s) {
        int len = 0;
        if (s == null)
            return len;
        char[] ch = s.toCharArray();

        Set<Character> set = new HashSet<>();
        int p = 0, q = 0;

        while (q < ch.length) {
            if (!set.contains(ch[q])) {
                set.add(ch[q]);
                q++;
                len = Math.max(len, set.size());
            } else {
                set.remove(ch[p]);
                p++;
            }
        }
        return len;
    }

    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring("abcabcbb"));
        System.out.println(lengthOfLongestSubstring("bbbbbb"));
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容