*LeetCode--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'.
自己的做法:(很麻烦)
利用回文的特性,准备两个指针,left = 0, right = s.length() - 1
然后依次向中间移动,同时判断s.charAt(left) == s.charAt(right)
当遇到不等的地方,记录是第几次不等,flag = 0则进行下面的操作,否则是第二次的不等,直接返回false,
进行操作判断,如果s.charAt(left + 1) 和s.charAt(right)是否相同,此时还有一种情况就是 s.charAt(left) 和s.charAt(right - 1)也相同
这样就得分情况讨论 如下面的 2位置的 c 和后面的 u,以及他们对应的 u 和 c
mlcupuuffuupuculm
class Solution {
public boolean validPalindrome(String s) {
if(s == null || s.length() == 0) return true;
int left = 0;
int right = s.length() - 1;
int flag = 0;
while(left < right){
if(s.charAt(left) != s.charAt(right)){
if(flag == 0){
flag = 1;
if(left + 1 < right && s.charAt(left + 1) == s.charAt(right)) {
if (s.charAt( left ) == s.charAt( right - 1 )) {
if (s.charAt( left + 2 ) == s.charAt( right - 1 )) {
left++;
} else {
right--;
}
} else{
left++;
}
} else{
right--;
}
}else {
return false;
}
} else {
left++;
right--;
}
}
return true;
}
}
discuss区看到比较简单的方法:是左边加1或者右边减1都考虑一下,进行或运算,结果就是了。
class Solution {
public boolean validPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j && s.charAt(i) == s.charAt(j)) {
i++; j--;
}
if (i >= j) return true;
if (isPalin(s, i + 1, j) || isPalin(s, i, j - 1)) return true;
return false;
}
private boolean isPalin(String s, int i, int j) {
while (i < j) {
if (s.charAt(i) == s.charAt(j)) {
i++; j--;
}
else return false;
}
return true;
}
}

浙公网安备 33010602011771号