LeetCode#680: Valid Palindrome II
阿新 • • 發佈:2018-11-17
Description
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
Example
Input: "aba"
Output: True
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.
Solution
考慮這個測試用例: mlcupuuffuupuculm
,當判斷到'c' != 'u'
的時候,我們要選擇究竟是刪除’c’還是’u’,因為無論刪除哪個字元,下一個要比較的字元都相等,然而再往下就不一定相等了。因此,我們用return isPalindrome(s, i+1, j) || isPalindrome(s, i, j-1);
判斷分別刪除’c’和’u’之後的字串是否是迴文,而在這個判斷的過程中,如果再發現有字元不相等,根據題目要求只允許刪除一個字元,因此直接返回false。
這種解法有可能第一個字串就不相等,轉而執行isPalindrome(s, i+1, j)
||
再執行isPalindrome(s, i, j-1);
,也就是說,整個操作最多掃描陣列2 * n次,因此時間複雜度為O(n)。
public class Solution {
public boolean validPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
while(i < j) {
if(s.charAt(i) != s.charAt(j))
return isPalindrome (s, i+1, j) || isPalindrome(s, i, j-1);
i++;
j--;
}
return true;
}
private boolean isPalindrome(String s, int i, int j) {
while(i < j) {
if(s.charAt(i) != s.charAt(j)) return false;
i++;
j--;
}
return true;
}
}