zoukankan      html  css  js  c++  java
  • LeetCode Longest Palindromic Substring

    Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

    如果一个字符串从左向右写和从右向左写是一样的,这样的字符串就叫做palindromic string,如aba,或者abba。本题是这样的,给定输入一个字符串,要求输出一个子串,使得子串是最长的padromic string。

     1 public class Solution {
     2     public String longestPalindrome(String s) {
     3         String longets = "";
     4         if (s.length() <= 1) {
     5             return s;
     6         }
     7         boolean[][] isP = new boolean[s.length()][s.length()];
     8         for (int i = 0; i < s.length(); i++) {
     9             isP[i][i] = true;
    10         }
    11         for (int i = 0; i < s.length()-1; i++) {
    12             if (s.charAt(i) == s.charAt(i + 1)) {
    13                 isP[i][i + 1] = true;
    14                 longets = s.substring(i, i + 2);
    15             }
    16         }
    17 
    18         for (int l = 3; l <= s.length(); l++) {
    19             for (int i = 0; i <= s.length() - l; i++) {
    20                 int j = i + l - 1;
    21                 if (s.charAt(i) == s.charAt(j)) {
    22                     isP[i][j] = isP[i + 1][j - 1];
    23                     if (isP[i][j] && l > longets.length()) {
    24                         longets = s.substring(i, j + 1);
    25                     }
    26                 }
    27             }
    28         }
    29         return longets;
    30 
    31     }
    32 
    33 
    34 }
  • 相关阅读:
    python3内置函数大全
    字符串格式化及函数
    基础数据和编码
    python基本数据类型
    python基础
    python re模块
    python json模块
    python os模块
    python random模块
    python time模块
  • 原文地址:https://www.cnblogs.com/birdhack/p/4162119.html
Copyright © 2011-2022 走看看