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.

解题思路一:

暴力枚举

共N^2量级个子串(从下标零开始),每次检查需一个for循环,等于是3重for循环,时间复杂度O(n^3)

解题思路二:

动态规划

设定一个表格table[][],其中table[i][j]表示substring(i,j+1)是不是Palindromic,时间复杂度为O(n^2)空间复杂度也为O(n^2)。

Java代码如下:

	static public String longestPalindrome(String s) {
if(s.length()==1)return s;
int[][] table=new int[s.length()][s.length()];
int beginIndex = 0,endIndex = 0;
//初始化第一、第二条斜线
for(int i=0;i<s.length();i++){
table[i][i]=1;
if(i==s.length()-1)break;
if(s.charAt(i)==s.charAt(i+1)){
table[i][i+1]=1;
beginIndex=i;
endIndex=i+1;
}
}
//给第k条斜线赋值
for(int k=2;k<s.length();k++){
for(int i=0;i<s.length()-k;i++){
if(table[i+1][i+k-1]==1&&s.charAt(i)==s.charAt(i+k)){
table[i][i+k]=1;
beginIndex=i;
endIndex=i+k;
}
}
}
printTable(table);
return s.substring(beginIndex,endIndex+1);
} public static void printTable(int table[][]){
for(int i=0;i<table.length;i++){
for(int j=0;j<table[i].length;j++){
System.out.print(table[i][j]+" ");
}
System.out.println("");
}
}

提交结果,TimeExceed。证明时间复杂度为O(n^2)是不能提交通过的。

解题思路三:

中心法,对S中每一个字符及重复的双字符为中心,进行遍历。时间复杂度为O(n^2),在leetcode上竟然Accepted!

Java代码如下:

static public String longestPalindrome(String s) {
if (s.length() == 1) return s;
String longest = s.substring(0, 1);
for (int i = 0; i < s.length(); i++) {
// 检查单字符中心
String tmp = helper(s, i, i);
if (tmp.length() > longest.length())
longest = tmp;
// 检查多字符中心
tmp = helper(s, i, i + 1);
if (tmp.length() > longest.length())
longest = tmp;
} return longest;
}
public static String helper(String s, int begin, int end) {
while (begin >= 0 && end <= s.length() - 1 && s.charAt(begin) == s.charAt(end)) {
begin--;
end++;
}
return s.substring(begin + 1, end);
}

解题思路四:

Manacher’s algorithm,时间复杂度为O(n)

算法思路比较复杂,参考链接

http://blog.csdn.net/ggggiqnypgjg/article/details/6645824

http://blog.csdn.net/xingyeyongheng/article/details/9310555

Java代码

	static public String longestPalindrome(String s) {
char[] sChar = new char[2 * s.length() + 1];
for (int i = 0; i < sChar.length; i++) {
if (i % 2 == 0)
sChar[i] = '#';
else
sChar[i] = s.charAt(i / 2);
} int[] p = new int[2 * s.length() + 1];
int id = 0, mx = 0, maxID = 0;
for (int i = 0; i < sChar.length; i++) {
// 核心算法
if (mx > i) {
p[i] = Math.min(p[2 * id - i], mx - i);
} else
p[i] = 1;
int low = i - p[i], high = i + p[i];
while (low >= 0 && high <= (sChar.length - 1)) {
if (sChar[low] == sChar[high]) {
p[i]++;
low--;
high++;
} else
break;
}
// 更新id和mx的值
if (i + p[i] > mx) {
id = i;
mx = id + p[i];
}
// 更新取得最大p【i】的id
if (p[maxID] < p[i])
maxID = i;
}
char[] result = new char[p[maxID] - 1];
for (int i = 0; i < result.length; i++) {
result[i] = sChar[maxID - p[maxID] + 2 + 2 * i];
}
return new String(result);
}

C++实现如下:

 #include<string>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
vector<char> sChar( * s.length() + , '#');
for (int i = ; i < sChar.size(); i++)
if(i&)
sChar[i]= s[i / ];
vector<int> p( * s.length() + ,);
int id = , mx = , maxID = ;
for (int i = ; i < sChar.size(); i++) {
// 核心算法
if (mx > i) {
int temp = p[ * id - i];
p[i] =min(temp, mx - i);
}
else
p[i] = ;
int low = i - p[i], high = i + p[i];
while (low >= && high <= (sChar.size() - )) {
if (sChar[low] == sChar[high]) {
p[i]++;
low--;
high++;
}
else
break;
}
if (i + p[i] > mx) {
id = i;
mx = id + p[i];
}
if (p[maxID] < p[i])
maxID = i;
}
vector<char> result(p[maxID] - ,'');
for (int i = ; i < result.size(); i++) {
result[i] = sChar[maxID - p[maxID] + + * i];
}
string res;
res.assign(result.begin(), result.end());
return res;
}
};

【JAVA、C++】LeetCode 005 Longest Palindromic Substring的更多相关文章

  1. 【JAVA、C++】LeetCode 003 Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. For example, ...

  2. 【JAVA、C++】LeetCode 014 Longest Common Prefix

    Write a function to find the longest common prefix string amongst an array of strings. 解题思路: 老实遍历即可, ...

  3. 【JAVA、C++】LeetCode 002 Add Two Numbers

    You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...

  4. 【JAVA、C++】LeetCode 022 Generate Parentheses

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  5. 【JAVA、C++】LeetCode 010 Regular Expression Matching

    Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...

  6. 【JAVA、C++】 LeetCode 008 String to Integer (atoi)

    Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...

  7. 【JAVA、C++】LeetCode 007 Reverse Integer

    Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 解题思路:将数字 ...

  8. 【JAVA、C++】LeetCode 006 ZigZag Conversion

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

  9. 【JAVA、C++】LeetCode 004 Median of Two Sorted Arrays

    There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two ...

随机推荐

  1. 『jQuery』.html(),.text()和.val()的概述及使用

    转自http://www.jb51.net/article/35867.htm 如何使用jQuery中的.html(),.text()和.val()三种方法,用于读取,修改元素的html结构,元素的文 ...

  2. BZOJ-4300 绝世好(蛋疼)题 DP(递推)

    翻zky学长的blog时翻出来的..... 4300: 绝世好题 Time Limit: 1 Sec Memory Limit: 128 MB Submit: 736 Solved: 393 [Sub ...

  3. Spring的辅助类

    http://www.cnblogs.com/maoan/p/3446224.html spring获取ApplicationContext对象的方法——ApplicationContextAware

  4. Laravel 5.3 中文文档翻译完成

    经过一个多月的紧张翻译和校对,翻译完成.以下是参与人员: Laravel 5.3 中文文档翻译完成 稿源:七星互联www . qixoo.com 文档地址在此:https://laravel-chin ...

  5. Java中各种(类、方法、属性)访问修饰符与修饰符的说明

    类: 访问修饰符 修饰符 class 类名称 extends 父类名称 implement 接口名称 (访问修饰符与修饰符的位置可以互换) 访问修饰符 名称 说明 备注 public 可以被本项目的所 ...

  6. i++和++i

    这个问题总是讨论,有时又被弄晕了,特来复习一下 ; ; cout<<s<<endl; cout<<5,而i+++4返回4,其实这样的i++先运算,再加,++i先加再 ...

  7. json中loads的用法

    python中json中的loads()和dumps()它们的作用经常弄换了,这里记录下,loads方法是把json对象转化为python对象,dumps方法是把pyhon对象转化为json对象,我是 ...

  8. epoch iteration batchsize

    深度学习中经常看到epoch. iteration和batchsize,下面按自己的理解说说这三个的区别: (1)batchsize:批大小.在深度学习中,一般采用SGD训练,即每次训练在训练集中取b ...

  9. SqlServer 连接字符串多种配置

    Application Name(应用程序名称):应用程序的名称.如果没有被指定的话,它的值为.NET SqlClient Data Provider(数据提供程序). AttachDBFilenam ...

  10. 5个常用Java代码混淆器 助你保护你的代码

    [IT168 技术文档] 从事Java编程的人都知道,可以通过逆向工程反编译得到Java程序的源代码,这种反编译工具之一就是JAD.因此,为保护我们的劳动成果,尽可能给反编译人员制造障碍,我们可以使用 ...