Java Two Pointers with BitSet


  • 0
    A

    Haven't tried to shorten the code.

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            if (s==null) return 0;
            if (s.length()<2) return s.length();
            BitSet b = new BitSet(256);
            int ptr1=0, ptr2=0, len=s.length(), max=0, count=0;
            while (ptr1<=ptr2 && ptr2<len) {
                char c = s.charAt(ptr2);
                if (!b.get(c)) {
                    b.set(c);
                    ptr2++;
                    count++;
                } else {
                    max = Math.max(count, max);
                    count=0;
                    b.clear();
                    ptr1++;
                    ptr2=ptr1;
                }
                max = Math.max(count, max);
            }
            return max;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.