two pointer的简单实例
time complexisty O(n), space complexisty O(1)
two pointer跟binary search不要搞混了,binary search的每次计算量减半,所以time complexisty O(logn)
- 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;
}
};
- 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;
}
};