zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    

    效率提高

    拓展问题

  • 相关阅读:
    Word+PS制作拼音表格
    VC6.0 突然打不开dsw 工程文件的解决方案
    C# 字符串的连接
    ASP.NET中弹出消息框的几种常见方法
    用五分钟重温委托,匿名方法,Lambda,泛型委托,表达式树
    WPF 显示模态窗口和窗体
    mysql5.5安装图解
    Microsoft Visual Studio 2010 Service Pack 1(exe)
    HTTP错误 404.17
    2014-2-7
  • 原文地址:https://www.cnblogs.com/clnsx/p/12307386.html
Copyright © 2011-2022 走看看