680. 验证回文串 II
点击上方标题跳转至leetcode
题目描述
给你一个字符串 s
,最多 可以从中删除一个字符。
请你判断 s
是否能成为回文字符串:如果能,返回 true
;否则,返回 false
。
示例 1:
输入:s = "aba" 输出:true
示例 2:
输入:s = "abca" 输出:true 解释:你可以删除字符 'c' 。
示例 3:
输入:s = "abc" 输出:false
提示:
1 <= s.length <= 105
s
由小写英文字母组成
解题
Python3
class Solution:
def validPalindrome(self, s: str) -> bool:
def checkPalindrome(low, high):
i, j = low, high
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
low, high = 0, len(s) - 1
while low < high:
if s[low] == s[high]:
low += 1
high -= 1
else:
return checkPalindrome(low + 1, high) or checkPalindrome(low, high - 1)
return True
fun = Solution()
s = "abc"
res = fun.validPalindrome(s)
print(res)
C++
#include<iostream>
#include<string.h>
using namespace std;
class Solution {
public:
bool checkPalindrome(const string& s, int low, int high) {
for (int i = low, j = high; i < j; ++i, --j) {
if (s[i] != s[j]) {
return false;
}
}
return true;
}
bool validPalindrome(string s) {
int low = 0,high =s.size() -1;
while(low<high){
char c1 = s[low],c2 = s[high];
if(c1 == c2){
++low;
--high;
}
else{
return checkPalindrome(s,low+1,high)|| checkPalindrome(s,low,high-1);
}
}
return true;
}
};
int main(){
string s ="abca";
// string s ="abc";
bool res = Solution().validPalindrome(s);
cout << res << endl;
return 0;
}
//g++ 680.cpp -std=c++11
标签:high,return,int,0680,II,low,true,Leetcode,checkPalindrome
From: https://www.cnblogs.com/yege/p/17373284.html