Two Pointers

1 3 Longest Substring Without Repeating Character  map维护最长里的值 ,两个指针向前移动

    public int lengthOfLongestSubstring(String s) {
        if (s.length() == 0) return 0;
        HashMap<Character, Integer> map =  new HashMap<>();
        int max = 0;
        for (int j = 0, i = 0; i < s.length(); i++)
        {
            if (map.containsKey(s.charAt(i)))
            {
                j = Math.max(j, map.get(s.charAt(i)) + 1);
            }
            map.put(s.charAt(i),i);
            max = Math.max(max, i - j + 1);
        }
        return max;
    }
View Code

2 28 Implement strStr()    变量两字符分三种情况

    public int strStr(String haystack, String needle) {
        for (int i = 0; ; i++)
        {
            for (int j = 0;; j++)
            {
                if (j == needle.length()) return i;
                if (i + j == haystack.length()) return -1;
                if (needle.charAt(j) != haystack.charAt(j + i)) break;
            }
        }
    }
View Code

3 125 Valid palindrome     前后两指针 ,用idletterordigit

    public boolean isPalindrome(String s) {
        if (s.isEmpty()) return true;
        int l = 0, r = s.length() - 1;
        char lc , rc;
        while (l < r)
        {
            lc = s.charAt(l);
            rc = s.charAt(r);
            if (!Character.isLetterOrDigit(lc)) l++;
            else if (!Character.isLetterOrDigit(rc)) r--;
            else
            {
                if (Character.toLowerCase(lc) != Character.toLowerCase(rc)) {
                    return false;
                }
                l++; r--;
            }
        }
        return true;
    }
View Code

4 159 Longest

        int lengthOfLongestSubstringTwoDistinct(String s) {
            int res = 0, l = 0, low = 0;
            HashMap<Character, Integer> map = new HashMap<>();
            for (int i = 0; i < s.length(); i++)
            {
                map.put(s.charAt(i), i);
                if (map.size() > 2)
                { 
                    l = i;
                    for (int n : map.values())
                    {
                        l = Math.min(n,l);
                    }
                    map.remove(s.charAt(l));
                    low = l + 1;
                }
                res = Math.max(res, i - low + 1);
            }
            return res;
        }
View Code
原文地址:https://www.cnblogs.com/whesuanfa/p/6773107.html