Leetcode: two pointers
阿新 • • 發佈:2018-12-21
two pointer的簡單例項
time complexisty O(n), space complexisty O(1)
two pointer跟binary search不要搞混了,binary search的每次計算量減半,所以time complexisty O(logn)
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; } };
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; } };