美文网首页
Longest Substring Without Repeat

Longest Substring Without Repeat

作者: 浪子_byte | 来源:发表于2019-04-23 14:21 被阅读0次
    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"));
        }
    }
    

    相关文章

      网友评论

          本文标题:Longest Substring Without Repeat

          本文链接:https://www.haomeiwen.com/subject/ejevgqtx.html