680. Valid Palindrome II
阿新 • • 發佈:2018-01-20
一個 lin 2.3 回文 pre color valid bsp ati
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、要是兩個都不符合條件,那就說明只刪除一個元素不能形成回文。
class Solution { public: bool validPalindrome(string s) { intlow = 0; int high = s.length() - 1; int cnt = 0; while (low<high) { if (s[low] != s[high]) { if (s[low+1] == s[high] && s[low] == s[high-1]) { if (s[low+1] == s[high] && s[low+2] == s[high-1])++low; else if (s[low] == s[high-1] && s[low+1] == s[high-2]) --high; } else if (s[low+1] == s[high]) ++low; else if (s[low] == s[high-1]) --high; else return false; ++cnt; } if (cnt==2) return false; ++low; --high; } return true; } };
680. Valid Palindrome II