标签:rip empty str 删除 imu while only abc tput
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:
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指针从头和从尾比较即可。
不匹配时删除左边的字符还是右边的字符才能匹配,所以左右两边都要试一下
标签:rip empty str 删除 imu while only abc tput
原文地址:https://www.cnblogs.com/chanaichao/p/9638561.html