最长回文字串
来源:互联网 发布:阿里云华北5是哪里 编辑:程序博客网 时间:2024/05/29 07:08
基本思想
将string A用“#”补齐为奇数长度的字符串B,然后构建H数组,将B中的所有回文长度填充进去,最后遍历整个H数组找max, 返回max-1
A: 1223 –> B:#1#2#2#3#
最后时刻H为[1,2,1,2,3,2,1,2,1];
C++实现
#include <iostream>#include <vector>using namespace std;bool check(const string& str){ string _str = str; reverse(_str.begin(), _str.end()); return _str==str;}//A为所需判断字符串,n为字符串长度int getLongestPalindrome(string A, int n) { // write code here int l = 1+2*n; vector<int> H = vector<int>(l,0); string B = "#"; for(int i=0; i<n; ++i){ B += A.substr(i,1); B += "#"; } cout<<B<<endl; for(int i=0; i<l; ++i){ int j=0; int lindex=0; int rindex=0; while(1){ lindex = i-j; rindex = i+j; if(lindex>=0 && rindex<=l-1){ string _str = B.substr(lindex, (rindex-lindex+1)); if(check(_str)){ H[i]++; j++; } else{ break; } } else{ break; } } for(int j=0; j<l; j++){ if(j==l-1){ cout<<H[j]<<endl; break; } cout<<H[j]; } } int max=0; for(int j=0; j<l; j++){ if(max<H[j]) max=H[j]; } return max-1;}int main(){ cout<<getLongestPalindrome("1223",4); //result = 2}
0 0
- 最长回文字串
- 求解最长回文字串
- 最长回文字串
- 最长回文字串
- 最长回文字串
- 最长回文字串
- 最长回文字串
- hihocoder1032:最长回文字串
- 最长回文字串 lintcode
- 求最长回文字串
- 最长回文字串
- 最长回文字串
- 字符串的最长回文字串
- hdu 3068 最长回文字串
- 最长回文字串-manacher算法
- poj_1974,最长回文字串manacher
- C 最长回文字串问题
- 最长回文字串的提取
- Oracle数据库导入导出语法
- 底部弹出PopupWindow并且背景变为半透明效果
- CSS 垂直居中
- java 时间与字符串之间的转换
- sql语句优化
- 最长回文字串
- JNI使用的一些实现
- Flume内置channel,source,sink三组件介绍
- ionic 打电话
- AQS的原理浅析
- leetcode102. Binary Tree Level Order Traversal
- Gson解析 并反转
- 作业博客4
- React Native 之弹性(Flex)宽高