Difficulty:easy

 More:【目录】LeetCode Java实现

Description

https://leetcode.com/problems/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'.

Intuition

1.Make use of two pointers.

 

Solution

    public boolean validPalindrome(String s) {
        for(int i = 0, j = s.length()-1; i < j; i++,j--){
            if(s.charAt(i) != s.charAt(j))
                return isPalindrome(s, i, j-1) || isPalindrome(s, i+1, j);
        }
        return true;
    }
    
    private boolean isPalindrome(String s, int i, int j){
        while(i < j){
            if(s.charAt(i++) != s.charAt(j--))
                return false;
        }
        return true;
    }

  

Complexity

Time complexity : O(n)

Space complexity : O(1)

 

What I've learned

1. It's important to learn and make use of the method isPalindrome() 

 More:【目录】LeetCode Java实现

 

相关文章:

  • 2021-11-20
  • 2022-02-26
  • 2022-12-23
  • 2022-03-04
  • 2021-10-19
  • 2022-01-30
  • 2021-09-27
  • 2021-09-14
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-20
  • 2022-12-23
  • 2021-09-17
  • 2022-01-28
  • 2022-12-23
相关资源
相似解决方案