[leetcode]680. Valid Palindrome II有效回文II(可至多刪一原字符)
阿新 • • 發佈:2018-10-18
span cti pan col rac helper code delet example
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‘.
思路:
代碼:
1 class Solution { 2 public boolean validPalindrome(String s) {3 int l = 0; 4 int r = s.length()-1; 5 while(l < r){ 6 if(s.charAt(l) != s.charAt(r)){ 7 // try to delete a left side char || delete a right side char 8 return isPalin(s, l+1,r) || isPalin(s, l,r-1); 9 }else{ 10 l++;11 r--; 12 } 13 } 14 return true; 15 16 } 17 18 // helper function to judge valid palindrome 19 private boolean isPalin(String s , int l, int r){ 20 while(l < r){ 21 if(s.charAt(l++)!=s.charAt(r--)) returnfalse; 22 } 23 return true; 24 } 25 }
[leetcode]680. Valid Palindrome II有效回文II(可至多刪一原字符)