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.
题目链接:https://leetcode-cn.com/problems/valid-palindrome-ii/
思路
简单的判断,逻辑直接翻译代码。
class Solution {
public:
bool validPalindrome(string s) {
int l = 0, r = s.size()-1;
while(l<r){
if(s[l]!=s[r]){
return valid(s, l, r-1) || valid(s, l+1, r);
}
++l;
--r;
}
return true;
}
bool valid(string s, int l, int r){
while(l<r){
if(s[l]!=s[r]){
return false;
}
++l;
--r;
}
return true;
}
};

本文介绍了解决LeetCode上第680题验证回文字符串 II的方法,该题要求判断是否可以通过删除一个字符使给定字符串成为回文。文章提供了一个简洁的C++代码实现,通过双指针从两端向中间遍历,遇到不匹配字符时分别尝试跳过左或右字符检查剩余部分是否为回文。

被折叠的 条评论
为什么被折叠?



