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.
這道題是之前那道Valid Palindrome的擴充,還是讓我們驗證回覆字串,但是區別是這道題的字串中只含有小寫字母,而且這道題允許刪除一個字元,那麼當遇到不匹配的時候,我們到底是刪除左邊的字元,還是右邊的字元呢,我們的做法是兩種情況都要算一遍,只要有一種能返回true,那麼結果就返回true。我們可以寫一個子函式來判斷字串中的某一個範圍內的子字串是否為迴文串,參見程式碼如下:
解法一:
class Solution { public: bool validPalindrome(string s) { int left = 0, right = s.size() - 1; while (left < right) { if (s[left] != s[right]) return isValid(s, left, right - 1) || isValid(s, left + 1, right); ++left; --right; } return true; } bool isValid(string s, int left, int right) { while (left < right) { if (s[left] != s[right]) return false; ++left; --right; } return true; } };
下面這種寫法跟上面的解法思路一樣,只不過沒有寫額外的函式,還是要遍歷兩種情況,參見程式碼如下:
解法二:
class Solution { public: bool validPalindrome(string s) { int left = 0, right = s.size() - 1; while (left < right) { if (s[left] == s[right]) { ++left; --right; } else { int l = left, r = right - 1; while (l < r) { if (s[l] != s[r]) break; ++l; --r; if (l >= r) return true; } ++left; while (left < right) { if (s[left] != s[right]) return false; ++left; --right; } } } return true; } };
類似題目:
參考資料:
https://discuss.leetcode.com/topic/103939/java-o-n-time-o-1-space
https://discuss.leetcode.com/topic/103911/two-solutions-optimized-and-recursive-java-and-c