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

分析过程

  • 题目归类:
    回文题目。

  • 题目分析:
    本题归为eazy是有问题的。虽然可以采用穷举法(删除每一个字母来判断是不是palindrome),但是作为有志向的,怎么能拘泥于此,想想如何把时间缩短而不是O(n^2)
    可以这么考虑:
    l = 0; r = s.length()-1;
    当s.charAt(l) != s.charAt(r)时,就判断删除l或者删除r
    这是因为,只能有一个不一样,所以我们删除了后必须是palindrome。

  • 边界分析:

    • 空值分析
    • 循环边界分析
  • 方法分析:

    • 数据结构分析
    • 状态机
    • 状态转移方程
    • 最优解
  • 测试用例构建

代码实现

class Solution {
    public boolean validPalindrome(String s) {
        int l = -1,r = s.length();
        while(l<r){
            if(s.charAt(++l)!=s.charAt(--r)){
                return Palindrome(s,l+1,r)||Palindrome(s,l,r-1);
            }
        }
        return true;
    }
    public boolean Palindrome(String s,int l, int r) {
        while(l<r){
            if(s.charAt(l++)!=s.charAt(r--)){
                return false;
            }
        }
        return true;
    }
}

效率提高

拓展问题

posted @ 2020-02-14 14:42  clnsx  阅读(75)  评论(0编辑  收藏  举报