题目:
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。
解答:
1 class Solution { 2 public boolean validPalindrome(String s) { 3 int left=0,right=s.length()-1; 4 while(left<right){ 5 if(s.charAt(left)!=s.charAt(right)) 6 return isValid(s,left+1,right) || isValid(s,left,right-1); 7 left++;right--; 8 } 9 return true; 10 } 11 12 public boolean isValid(String s,int left,int right){ 13 while(left<right){ 14 if(s.charAt(left)!=s.charAt(right)) 15 return false; 16 left++;right--; 17 } 18 return true; 19 } 20 }
详解:
字符串判断回文,设置left,right指针从头和从尾比较即可。
不匹配时删除左边的字符还是右边的字符才能匹配,所以左右两边都要试一下
原文地址:https://www.cnblogs.com/chanaichao/p/9638561.html
时间: 2024-10-16 15:23:46