JonsenElizee

Software Developing Blog

"An idea is fragile . It can be killed by a scornful smile or a yawn .It can be mound down by irony and scared to death by a cold look."
"Most cultures throughout human history have not liked creative individuals .They ignore them or kill them.It is a very efficient way of stopping creativity."

------Advertising boss Charles Browe and Howard Gardner ,professor at Harvard

   :: 首页 :: 新随笔 ::  ::  :: 管理 ::
Here is my simple recursive implementation for this issue.
Without full test.
If any bug, please let me know. thank you so much.

Anybody could show me a non-recursive right implementation for this question?
On internet, many implementation can not pass my simple test.
And I spent much time on this issue and no good resolution gained even now.
So, I hope you can write a nice non-recursive one and post on this page. thank you again.

the best from Jonsen.

#include <stdio.h>
#include 
<string.h>
static int len = 0;
static char* str = NULL;

/**
 * find all possible palindromes starting with str[m]
 
*/
int scan(int m, int n){
    
if(m > n) return 0;
    
int i = m, j = n;
    
while(i < j){
        
if(str[i] == str[j]) { i++; j--; }
        
else break;
    }
    
if(i >= j) return n-m+1;
    
else return scan(m, n-1);
}

/**
 * process str starting with m and ending with n.
 * then, process str starting with m+1, and ending with n.
 * if length of string is smaller than len gained, there is
 * no need to process the str anymore and avoiding useless 
 * processing.
 
*/
void process(int m, int n){
    printf(
"process(%d, %d)\n", m, n);
    
if(m > n) return;
    
int tmp = scan(m, n);
    printf(
"scan(%d, %d) and rtv = %d\n", m, n, tmp);
    len 
= tmp > len ? tmp : len;
    
if(n-> len) process(m+1, n);
}

int main(int argc, char* argv[]){
    str 
= argv[1];
    process(
0, strlen(str) - 1);
    printf(
"len = %d\n", len);
    
return 0;
}

Running log:
[root@localhost tmp]# gcc longest_palindrome_substring.c && time a.out abcabcddcbbcddcba
process(
016)
scan(
016) and rtv = 1
process(
116)
scan(
116) and rtv = 1
process(
216)
scan(
216) and rtv = 1
process(
316)
scan(
316) and rtv = 14
len 
= 14

real    0m0.001s
user    0m0.000s
sys     0m0.001s
[root@localhost tmp]# 


posted on 2010-10-10 23:10 JonsenElizee 阅读(1537) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


By JonsenElizee