LeetCode 680. Valid Palindrome II (验证回文字符串 Ⅱ)

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'.

 

Note:

  1. The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

 


题目标签:String

  题目给了我们一个String s,让我们判断它是否是palindrome,允许我们删除一个char。

  利用two pointers,left 和 right 从两边开始,问题在于,当遇到两个 char 不同的时候,我们需要分别删除left 和 right char 去判断它是不是 panlindrome,因为两个选择都有可能是palindrome。

  具体看code。

 

 

Java Solution:

Runtime beats 98.73% 

完成日期:04/20/2018

关键词:two pointers

关键点:用 || 来 测试两个选择性

 1 class Solution 
 2 {
 3     public boolean validPalindrome(String s) 
 4     {
 5         char [] arr = s.toCharArray();
 6         int left = 0;
 7         int right = arr.length - 1;
 8         
 9         while(left < right)
10         {
11             if(arr[left] != arr[right])
12             {
13                 return isPalindrome(arr, left + 1, right) || isPalindrome(arr, left, right - 1);
14             }
15 
16             left++;
17             right--;
18         }
19         
20         return true;
21     }
22     
23     
24     public boolean isPalindrome(char[] arr, int left, int right)
25     {
26         while(left < right)
27         {
28             if(arr[left] != arr[right])
29                 return false;
30             
31             left++;
32             right--;
33         }
34         
35         return true;
36     }
37 }

参考资料:https://leetcode.com/problems/valid-palindrome-ii/discuss/107716/Java-O(n)-Time-O(1)-Space

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2018-04-21 08:24  Jimmy_Cheng  阅读(404)  评论(0编辑  收藏  举报