LeetCode-680. Valid Palindrome II
https://leetcode.com/problems/valid-palindrome-ii/
题目描述
Given a string s, return true if the s can be palindrome after deleting at most one character from it.
Example 1:
Input: s = "aba" Output: true
Example 2:
Input: s = "abca" Output: true Explanation: You could delete the character 'c'.
Example 3:
Input: s = "abc" Output: false
Constraints:
1 <= s.length <= 105sconsists of lowercase English letters.
解题思路
【C++】
class Solution {
public:
bool validPalindrome(string s) {
int i = 0, j = s.length()-1;
while(i < j) if(s[i++] != s[j--]) return isPalindrome(s, i, j+1) || isPalindrome(s, i-1, j);
return true;
}
bool isPalindrome(string s, int i, int j) {
while(i < j) if(s[i++] != s[j--]) return false;
return true;
}
};
【Java】
class Solution {
public boolean validPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left++) != s.charAt(right--)) {
return isPalindrome(s, left, right + 1) || isPalindrome(s, left - 1, right);
}
}
return true;
}
public boolean isPalindrome(String s, int left, int right) {
while (left < right) {
if (s.charAt(left++) != s.charAt(right--)) {return false;}
}
return true;
}
}
5885



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



