Leetcode: two pointers

two pointer的简单实例
time complexisty O(n), space complexisty O(1)
two pointer跟binary search不要搞混了,binary search的每次计算量减半,所以time complexisty O(logn)

  1. Valid Palindrome
    https://leetcode.com/problems/valid-palindrome/description/
class Solution {
public:
    bool isPalindrome(string s) {
        int l = 0;
        int r = s.size() - 1;
        while( l < r)
        {
            while(l < r && !isalnum(s[l])) l++;
            while(l < r && !isalnum(s[r])) r--;
            if(toupper(s[l]) != toupper(s[r]))
            {
                return false;
            }
            l++;
            r--;
            
        }
        return true;
    }
};
  1. Valid Palindrome II
    https://leetcode.com/problems/valid-palindrome-ii/description/
class Solution {
public:
    bool validPalindrome(string s) {
        int l = 0;
        int r = s.size() - 1;
        bool res;
        while(l < r)
        {
            if(s[l] != s[r])
            {
                return (isValid(s, l+1, r) || isValid(s, l, r-1));
            }
            l++;
            r--;
        }
        
        return true;
        
    }
    
    bool isValid(string s, int i, int j)
    {
        while(i < j)
        {
            if(s[i++] != s[j--])
            {
                return false;
            }
            //i++;
            //j--;
        }
        
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43476349/article/details/84137667