【JAVA、C++】LeetCode 005 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.
解题思路一:
暴力枚举
共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的更多相关文章
- 【JAVA、C++】LeetCode 003 Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. For example, ...
- 【JAVA、C++】LeetCode 014 Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings. 解题思路: 老实遍历即可, ...
- 【JAVA、C++】LeetCode 002 Add Two Numbers
You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...
- 【JAVA、C++】LeetCode 022 Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- 【JAVA、C++】LeetCode 010 Regular Expression Matching
Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...
- 【JAVA、C++】 LeetCode 008 String to Integer (atoi)
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
- 【JAVA、C++】LeetCode 007 Reverse Integer
Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 解题思路:将数字 ...
- 【JAVA、C++】LeetCode 006 ZigZag Conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...
- 【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 ...
随机推荐
- collections_python
代码 import collections#counter继承字典的方法,items(),keys(),vavle() obj = collections.Counter('acbdafcbad') ...
- Hibernate中一级缓存和二级缓存使用详解
一.一级缓存二级缓存的概念解释 (1)一级缓存就是Session级别的缓存,一个Session做了一个查询操作,它会把这个操作的结果放在一级缓存中,如果短时间内这个 session(一定要同一个ses ...
- 德州扑克AI WEB版
继续之前的德州扑克话题,上次的DOS界面确实没法看,我女朋友说这是什么鬼.哈哈,估计只有自己能玩了 这两天重构了一下界面,基于web服务器和浏览器来交互. 服务器和客户端之间用websocket通信, ...
- springMVC实现防止重复提交
参考文档:http://my.oschina.net/mushui/blog/143397
- BZOJ2456 mode
Description 给你一个n个数的数列,其中某个数出现了超过n div 2次即众数,请你找出那个数. Input 第1行一个正整数n. 第2行n个正整数用空格隔开. Output 一行一个正整数 ...
- SQL Server中,Numric,Decimal,Money三种字段类型的区别
都是精确数据类型, 前两个可以自己定义长度和小数位数, Money的定义相当于Numric(19,4) numeric(10,2) 表示最大可以放10位数,但这10位数里有2位是小数如: 123456 ...
- C# ServiceStack.Redis 操作对象List
class Car { public Int32 Id { get; set; } public String Name { get; set; } static void Main(string[] ...
- abstract 类也可以继承 实体类
public class BaseReq { public String UserId { get; set; } public BaseReq() { } } public abstract cla ...
- Unity-Tween
1.GoKit 免费开源 AssetStore:https://www.assetstore.unity3d.com/en/#!/content/3663 下载地址:https://github.co ...
- TCP/IP协议栈概述
TCP/IP协议栈概述 这篇文章虽然只是很粗浅的介绍了ISO/OSI 网络模型,但确实把握住了关键点,某种意义上,简单回顾一下就可以加深对TCP/IP协议栈的理解. 原作者:阮一峰 链接: http: ...