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.
Input: "aba" Output: True
Input: "abca" Output: True Explanation: You could delete the character 'c'.
判断字符串是不是回文,最多可以删除字符串的一个元素来使它成为回文。
解决:从字符串两端开始比较,用一个指针low从前遍历,用high从尾部遍历。
1、当s[low] == s[high],说明符合回文,++low, --high,遍历下一组。
2、要是s[low] != s[high],就要删除一个数,重组。重组的原则就是s[low]和s[high-1]比较,s[high]和s[low+1]比较,是否能配对。
2.1、要是s[low+1] == s[high],那就删除当前的s[low];对应的s[low] == s[high-1],就删除当前的s[high]。
2.2、要是两个都符合条件,就要顺次看下一对能不能组合。
2.3、要是两个都不符合条件,那就说明只删除一个元素不能形成回文。
1 class Solution { 2 public: 3 bool validPalindrome(string s) { 4 int low = 0; 5 int high = s.length() - 1; 6 int cnt = 0; 7 while (low<high-1) { 8 if (s[low] != s[high]) { 9 while (s[low + 1] == s[high] && s[low] == s[high - 1]) { 10 ++low; 11 --high; 12 } 13 if (s[low + 1] == s[high]) 14 ++low; 15 else if (s[low] == s[high - 1]) 16 --high; 17 else 18 return false; 19 ++cnt; 20 } 21 if (cnt == 2) 22 return false; 23 ++low; 24 --high; 25 } 26 return true; 27 } 28 };