leetcode 第五题 最长回文子串
来源:互联网 发布:360网络攻防安全实验室 编辑:程序博客网 时间:2024/06/02 04:25
<pre name="code" class="cpp" style="font-size: 14px; line-height: 26px;"><span style="font-family: Arial; background-color: rgb(255, 255, 255);">http://www.tuicool.com/articles/n6NfIrN</span>
动态规划刚刚重新学,这道题实在想不出来,百度了一下才发现 动态规划的时间复杂度最少都n方。。。。。。。。。。方向就考虑错了,收到了leetcode第三题的影响。
回文字符串的子串也是回文,P[i][j](表示以i开始以j结束的子串)是回文字符串,那么P[i+1][j-1]也是回文字符串。该问题可以分解成一系列子问题。
定义状态方程和转移方程:
P[i][j]=0表示子串[i,j]不是回文串 P[i][j]=1表示子串[i,j]是回文串
dp[i][j] = (s[i] == s[j] && dp[i+1][j-1] == true)
class Solution {public: string longestPalindrome(string s) { int length = s.length(); if(length==1) return s; if(length==0) return NULL; bool dp[1000][1000] = {false}; int maxsublength = 0; int start = 0; for(int i=0;i<length;i++) { dp[i][i] = true; if(i<length-1 && s.at(i)==s.at(i+1)) { dp[i][i+1] = true; maxsublength = 2; start = i; } } for(int len = 3;len<=length;len++) { for(int i = 0;i<=length-len;i++) { int end = i+len-1; if(s.at(i) == s.at(end) && dp[i+1][end-1]) { dp[i][end] = true; if(len > maxsublength) {maxsublength = len;start = i; } } } } if(maxsublength>=2) return s.substr(start,maxsublength); return NULL; }};
0 0
- leetcode 第五题 最长回文子串
- leetcode 第五题 找到最长回文串
- leetcode:最长回文子串
- 第五章_最长回文子串
- leetcode第五题—最长回文字符串
- leetcode第5题,最长回文子串
- 【LeetCode 214】最长回文子串
- leetcode Problem 5 最长子回文串
- Leetcode 第九题:最长回文子字符串
- 每天一道LeetCode-----最长回文子串/序列,从头开始的最长回文子串长度
- 最长回文子串
- 最长回文子串
- 最长回文子串
- 最长回文子串
- 最长回文子串
- 最长回文子串
- 最长回文子串
- 最长回文子串
- java读取和生成表格
- 网络数据包转发和接收全过程
- jquery获取元素到屏幕四周可视距离
- C++基础复习心得3
- 小小的分享cell和edgsForExtenedLayout
- leetcode 第五题 最长回文子串
- 在Linux上安装SVN详解
- 图像卷积与滤波的一些知识点
- 生成式对抗网络GAN研究进展(五)——Deep Convolutional Generative Adversarial Nerworks,DCGAN
- 51Nod-1422-沙拉酱前缀
- Vmvare tools的作用
- 【Android】机房座位预约系统Android端
- C++单例模式以及线程安全
- Java: HttpURLConnection 使用多线程加快批量Post/Get的效率_20160918_七侠镇莫尛貝