美文网首页
leetcode的每日一题更新(Longest Palindro

leetcode的每日一题更新(Longest Palindro

作者: 今天是晴天 | 来源:发表于2017-09-22 17:06 被阅读0次

    Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
    Example:
    Input: "babad"
    Output: "bab"
    Note: "aba" is also a valid answer.
    Example:
    Input: "cbbd"
    Output: "bb"
    题目的意思就是找到最大回文字符子串。
    我的想法就是很简单的双重循环,遇到回文的记录,如果比记录的子串长就覆盖。
    代码刚开始用的是new StringBuilder(temp).reverse().toString()来判断是否是回文,代码没有问题,但是提交以后[Time Limit Exceeded],没有想到好的优化办法,感觉一直new对象出来可能会花很多时间,就重写了判断回文的算法,用最简单的切半头尾比较,把时间从380ms降到170左右,还是不行,再将外层循环变成从尾开始循环,时间可以降到120左右,也不行,实在没有办法,就去看别人的代码,居然看不懂,只有记录下来,继续学算法等以后再看,先附上我的代码

        public String longestPalindrome(String s) {
            if(s==null || s=="")return "";
            if(s.length()==1)return s;
            String result="";
            String temp="";
            result+=s.charAt(0);
            for(int i=0;i<s.length();i++) {
                for(int j=i;j<s.length();j++) {
                    temp+=s.charAt(j);
                    if(this.equal(temp) && result.length()<temp.length()) {
                        result=temp;
                    }
                }
                temp="";
            }
            return result;
        }
        public boolean equal(String temp) {
            for(int i=0;i<temp.length()/2;i++) {
                if(temp.charAt(i)!=temp.charAt(temp.length()-i-1)) {
                    break;
                }
                if(i==temp.length()/2-1 && temp.charAt(i)==temp.charAt(temp.length()-i-1)) {
                    return true;
                }
                
            }
            return false;
        }
    

    然后是网址上说用动态编程的方式[dynamic programming]
    捋了一个上午各种输出看结果来看算法的想法和思路都明白了,
    用一个n的二维boolean数组来记录回文,从后面开始循环,每一次i的循环中第一个都是设置为true,就是每行的第一个,例如dp[5][5],dp[4][4],但是第二次相等的时候,当记录第一对相等的字母时要么必须j-1<3要么这是第二个相等的字母,就是dp[i+1][j-1]为true,这样就能保证要么就是两个字母相连或者中间隔了一个字母的,要么就是继续是回文字符串,然后就更新返回的字符串res,如果dp[i][j]为真,并且res为null或者回文子串(j-i+1>res)的长度,更新字符串。

    public String longestPalindrome(String s) {
      int n = s.length();
      String res = null;
        
      boolean[][] dp = new boolean[n][n];
        
      for (int i = n - 1; i >= 0; i--) {
        for (int j = i; j < n; j++) {
          dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]);
                
          if (dp[i][j] && (res == null || j - i + 1 > res.length())) {
            res = s.substring(i, j + 1);
          }
        }
      }
        
      return res;
    }
    

    相关文章

      网友评论

          本文标题:leetcode的每日一题更新(Longest Palindro

          本文链接:https://www.haomeiwen.com/subject/mboxextx.html