编程系列之:最长回文子串问题
2008-04-04 09:22
281 查看
问题:
给定一个字符串,找出其中的最长回文子串长度。
例如:abccbabcddcba,最长的为abcddcba,长度为8
解决:
用栈,遇到与栈顶不同的字符,压栈;
否则,弹栈并比较下一个字符与栈顶的是否相同,相同继续弹栈;
记录弹了多少个,乘二,更新最长回文子串长度max;
/***
* starstarstarpku@gmail.com
* 20080404
*
* 找到给定字符串中最长的回文串长度。
* 例如:
* abccbabcddcba
* 最长的回文串是abcddcba长度为8
*/
#include <stdio.h>
#include <string.h>
#include "../../data_structure/stack/include/sim_stack.h"
#define BUFFSIZE 512
void solve (const char *p)
{
SimStack<char> stack;
/**
* 使用栈,如果当前字符与栈顶字符不同,则压栈;
* 遇到相同的字符,弹栈并顺次比较直到不再相同,
* 同时记录弹的字符数m;
* 回压栈m个字符。
* 继续压栈;
*/
int n = strlen(p);
int maxlen = 0;
for (int i=0; i<n; ) {
if (stack.size() <= 0 || stack.top() != p[i]) {
stack.push(p[i]);
i++;
continue;
}
int index_bk = i;
int popnum = 0;
while (stack.size() > 0 && i < n && stack.top() == p[i]) {
stack.pop();
i++;
popnum++;
}
// 记录最长回文子串长度
if (2*popnum > maxlen) {
maxlen = 2*popnum;
}
// 回压栈
for (int j=index_bk-popnum; j<index_bk+popnum; j++) {
stack.push (p[j]);
}
}
printf ("longest huiwen string length is: %d/n", maxlen);
}
int main (int argc, char **argv)
{
char str[BUFFSIZE];
printf ("input a str: /n");
scanf ("%s", str);
solve (str);
return 0;
}
给定一个字符串,找出其中的最长回文子串长度。
例如:abccbabcddcba,最长的为abcddcba,长度为8
解决:
用栈,遇到与栈顶不同的字符,压栈;
否则,弹栈并比较下一个字符与栈顶的是否相同,相同继续弹栈;
记录弹了多少个,乘二,更新最长回文子串长度max;
/***
* starstarstarpku@gmail.com
* 20080404
*
* 找到给定字符串中最长的回文串长度。
* 例如:
* abccbabcddcba
* 最长的回文串是abcddcba长度为8
*/
#include <stdio.h>
#include <string.h>
#include "../../data_structure/stack/include/sim_stack.h"
#define BUFFSIZE 512
void solve (const char *p)
{
SimStack<char> stack;
/**
* 使用栈,如果当前字符与栈顶字符不同,则压栈;
* 遇到相同的字符,弹栈并顺次比较直到不再相同,
* 同时记录弹的字符数m;
* 回压栈m个字符。
* 继续压栈;
*/
int n = strlen(p);
int maxlen = 0;
for (int i=0; i<n; ) {
if (stack.size() <= 0 || stack.top() != p[i]) {
stack.push(p[i]);
i++;
continue;
}
int index_bk = i;
int popnum = 0;
while (stack.size() > 0 && i < n && stack.top() == p[i]) {
stack.pop();
i++;
popnum++;
}
// 记录最长回文子串长度
if (2*popnum > maxlen) {
maxlen = 2*popnum;
}
// 回压栈
for (int j=index_bk-popnum; j<index_bk+popnum; j++) {
stack.push (p[j]);
}
}
printf ("longest huiwen string length is: %d/n", maxlen);
}
int main (int argc, char **argv)
{
char str[BUFFSIZE];
printf ("input a str: /n");
scanf ("%s", str);
solve (str);
return 0;
}
相关文章推荐
- [LeetCode系列] 最长回文子串问题
- 【 Javascript刷LeetCode系列】5. Longest Palindromic Substring 最长回文子串问题
- 编程之法:关于最长回文子串 | Manacher 算法详解
- Leetcode516.+Leetcode96. DP问题之求解最长回文子串+BST数目
- 最长回文子串问题
- hdu3068 最长回文子串问题.
- 最长回文子串(Longest Palindromic Substring)-DP问题
- 动态规划系列问题-最长公共子串
- 字符串系列之最长回文子串
- Manacher算法(最长回文子串问题)
- Manacher算法解决“最长回文子串”问题
- [编程之美-07]最长回文子串
- 最长公共子串(子序列)、最长递增子序列、最长回文子串等问题
- java 实现后缀数组及最长回文子串问题
- 算法的经典问题,求最长回文子串,最长重复字串
- 最长回文子串问题
- 【字符串处理系列】最长回文子串
- 字符串系列之最长回文子串
- 经典问题:最长回文子串
- 最长回文子串问题-Manacher算法