[leetcode-680-Valid Palindrome II]
Given a non-empty string s
, you may delete at most one character. Judge whether you can make it a palindrome.
Example 1:
Input: "aba" Output: True
Example 2:
Input: "abca" Output: True Explanation: You could delete the character 'c'.
Note:
- The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
思路:
从字符串两端向中间判断,如果相等则继续判断。
如果不相等,s[i] != s[j] ,那么判断 i+1到j 和i到j-1是否是回文,如果是的话即满足,都不是则不满足。
bool ispali(string& s,int start,int end) { while (start <= end) { if (s[start] != s[end])return false; start++, end--; } return true; } bool validPalindrome(string s) { int n = s.length(); if (n <= 2)return true; for (int i = 0; i < n;i++) { if (s[i] != s[n - i - 1]) { return (ispali(s, i + 1, n - i - 1) || ispali(s, i, n - i - 2)); } } return true; }
参考:
https://leetcode.com/problems/valid-palindrome-ii/solution/#approach-2-greedy-accepted