[Leetcode]Longest Palindromic Substring
2015-12-10 15:16
519 查看
Longest Palindromic Substring
Total Accepted: 82394 Total Submissions: 381112 Difficulty: Medium
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.
Subscribe to see which companies asked this question
使用暴力去做算法的时间复杂度肯定是O(n ^2),然后有一种叫做manacher的算法。可以把时间复杂度降到O(n)。详细的资料:戳这里
Total Accepted: 82394 Total Submissions: 381112 Difficulty: Medium
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.
Subscribe to see which companies asked this question
使用暴力去做算法的时间复杂度肯定是O(n ^2),然后有一种叫做manacher的算法。可以把时间复杂度降到O(n)。详细的资料:戳这里
class Solution { public: string longestPalindrome(string s) { int len = s.size(); if(!len) return ""; string str("$"); for(int i = 0;i <= len - 1;++ i){ str.push_back('#'); str.push_back(s[i]); } str.push_back('#'); len = str.size(); int id = 0; int maxDis = 0; vector<int> p(len,0); for(int i = 1;i <= len - 1;++ i){ if(maxDis > i){ p[i] = min(maxDis - i,p[2 * id - i]); } for(;str[i - p[i]] == str[i + p[i]];++ p[i]) ; if(i + p[i] > maxDis){ id = i; maxDis = i + p[i]; } } int maxLen = 0; int pos = 0; for(int i = 0;i <= p.size() - 1;++ i){ if(p[i] > maxLen){ maxLen = p[i]; pos = i; } } string res(str.substr(pos - maxLen + 1,maxLen * 2 - 1)); string ans; for(auto ch : res){ if(ch != '#'){ ans.push_back(ch); } } return ans; } };
相关文章推荐
- 【反思】:反思之计网考试前
- opencv 相关
- winForm程序生成安装包覆盖安装
- 设计模式之观察者模式
- 数据库高可用架构(MySQL、Oracle、MongoDB、Redis)
- C++库一览
- (小笔记),String 的各种用法,忘了,mark一下
- hdu 1856
- mysql 必知必会(1)
- scrollWidth,clientWidth,offsetWidth的区别
- Win7上配置Spark(1):Intellij IDEA上装Scala插件
- Java自动装箱与拆箱问题研究
- openwrt架构分析
- 蓝牙核心技术概述(五):蓝牙协议规范(irOBEX、BNEP、AVDTP、AVCTP)
- 代码片段
- 《软件需求最佳实践》——阅读笔记一
- 第7章 输入与输出
- oracle 判断是否数字 正则表达式法
- C# 获取时间差状态
- java的static块执行时机<转>