题目:
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
给定非空字符串 s, 您最多可以删除一个字符. 判断你是否可以成为回文.
- 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. 该字符串仅包含小写字符 a-z. 字符串的最大长度为 50000.
解答:
- 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 isValid(s,left+1,right) || isValid(s,left,right-1);
- left++;right--;
- }
- return true;
- }
- public boolean isValid(String s,int left,int right){
- while(left<right){
- if(s.charAt(left)!=s.charAt(right))
- return false;
- left++;right--;
- }
- return true;
- }
- }
详解:
字符串判断回文, 设置 left,right 指针从头和从尾比较即可.
不匹配时删除左边的字符还是右边的字符才能匹配, 所以左右两边都要试一下
来源: http://www.bubuko.com/infodetail-2765788.html