[英]find the longest palindrome
我想返回最長的回文,例如“civic”返回“civic”,“fawziizw”返回“wziizw”這是我試過的:
int ispalindrome (char str[],int start,int end) {
int i=0;
int j=0;
int counter=0;
for(i=start; i<strlen(str); i++) {
if (str[i]==str[end-i]){
counter++;
}
}
if(counter==i){
return counter;
} else
return 0;
}
void longestPalindrome(char str[]) {
int len = strlen(str);
int i=0;
int j=0;
int start=0;
Int end =0;
int counter=0;
int check=0;
if (strlen(str)-1==1||strlen(str)-1==2) {
printf("%s",str);
} else {
for (i=0; i<len; i++) {
counter=0;
for(j=len-1; j>=0; j--) {
if(str[i]==str[j]) {
counter= ispalindrome(str,i,j);
if (counter>check&&counter>0) {
check=counter;
start=i;
end=j;
}
}
}
}
for(i=start; i<=end; i++) {
printf("%c",str[i]);
}
}
}
所以它適用於像“civic”或“madam”這樣的回文,但是當我嘗試使用“fawziizw”時,它返回“f”而不是“wziizw”。
那太近了!
在 function ispalindrome()
中,您錯過了最后一個字符,因為start
可能不是0
,而i
從start
(>0) 開始會有end-i
錯過了字符串的結尾
int ispalindrome (char str[],int start,int end) {
int i=0;
int j=0;
int counter=0;
for(i=start; i<strlen(str); i++) {
if (str[i]==str[end-i]){ // <===== end-i not ok if start>0
counter++;
}}
if(counter==i){
return counter;}
else
return 0; // better to leave whenever it's not a palindrome
}
我建議一個更簡單的版本。 我們使用i
作為從0
開始的計數器,因為start
可能是>0
,以便在這種情況下不會錯過最后的字符
int ispalindrome (char str[],int start,int end) {
for(int i=0 ; i < end-start ; i++) {
if (str[start+i] != str[end-i]){
return 0; // <== return 0 if not a palindrome
}}
return end - start + 1;
}
然后它應該工作得更好。 在接下來的 function 中,您可以更改
for(j=len-1; j>=0; j--)
到
for(j=len-1; j>i; j--)
longestPalindrome
void longestPalindrome(char str[]) { int len = strlen(str); int i,j; int tempstart=0; int tempend=0; int counter; int tempcounter=0; for (i=0; i<len; i++) { for(j=len-1; j>i; j--) { // >i counter= ispalindrome(str,i,j); if (counter>=tempcounter&&counter>0) { tempcounter=counter; tempstart=i; tempend=j; } } } for(i=tempstart; i<=tempend; i++) { printf("%c",str[i]); } printf("\n"); }
這基本上是一樣的。
我已經做了這個定義長度的,並檢查是否有這個長度的任何子字符串(原始字符串的)是回文。
長度最初等於整個字符串的長度(因此,第一個子字符串實際上是整個原始字符串),並在每次迭代時減 1。 因此,找到的第一個回文子串是最長的回文串。
#include <stdio.h>
#include <string.h>
int ispalindrome(char *start, int length){
int i;
for(i=0; i < length-1-i; ++i){
if (start[i] != start[length-1-i]){
return 0;
}
}
return 1;
}
void longestPalindrome(char str[]) {
int lenstr, length, i, j;
lenstr = strlen(str);
for (length=lenstr; length > 0; --length){
for(i=0; length+i <= lenstr; ++i){
if(ispalindrome(str+i, length)){
for(j=0; j<length; ++j){
printf("%c", str[i+j]);
}
return;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.