您的位置:首页 > 其它

LeetCode Valid Palindrome II

2017-09-20 13:59 351 查看
原题链接在这里:https://leetcode.com/problems/valid-palindrome-ii/description/

题目:

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:

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

题解:

Valid Palindrome类似.

当出现错位时,或左或右向内移动一位.

Time Complexity: O(s.length()). Space: O(1).

AC Java:

1 class Solution {
2     public boolean validPalindrome(String s) {
3         int l = 0; int r = s.length()-1;
4         while(l<r){
5             if(s.charAt(l) != s.charAt(r)){
6                 return isPalindrome(s, l+1, r) || isPalindrome(s, l, r-1);
7             }
8             l++;
9             r--;
10         }
11         return true;
12     }
13
14     private boolean isPalindrome(String s, int l, int r){
15         while(l<r){
16             if(s.charAt(l) != s.charAt(r)){
17                 return false;
18             }
19             l++;
20             r--;
21         }
22         return true;
23     }
24 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: