標籤:

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.

代碼如下:

public boolean validPalindrome(String s) {n char[] sc = s.toCharArray();n int i = 0, j = s.length() - 1;n while(i < j){n if(sc[i] != sc[j]){n return helper(sc, i + 1, j) || helper(sc, i, j - 1);n }n i++;n j--;n }n return true;n }nn boolean helper(char[] sc, int i, int j){n while(i < j){n if(sc[i] != sc[j]) return false;n i++; j--;n }n return true;n } n

時間複雜度:O(N)

空間複雜度:O(1)

推薦閱讀:

leetcode-1
leetcode也開始收費了,大家怎麼看?
【LeetCode】005-最長迴文子串

TAG:LeetCode | 编程 |