0

找到C中第一个回文单词的开头?
例:Hello mom and dad, how is it going?
mom是第一个。

最有效的方法是什么?

char *find_first_palindrome(char *input)

4

3 回答 3

1

这是我的解决方案。它可以解决,但可能不是最有效的方法。希望它可以帮助你。

int find(char* c)//for single word
{
    int n=strlen(c);
    for(int i=0;i<n/2;i++)
    {
        if (c[i]!=c[n-i-1])
            return false;
    }
    return true;
}

char* findlong (char* lc)//for long sentence
{
    int i;
    char* end=lc+strlen(lc);
    for(;;)
    {
        for( i=0;lc[i];i++)
        {
            if(lc[i]==' ')
            {
                lc[i]='\0';
                break;
            }
        }
        if(find(lc) && !ispunct(*lc))//modified here,add !ispunct(*lc) to make it more robust.
            return lc;

        lc += i+1;
        if (lc>end)     //modified here. add this sentence.
        {
            printf("no word found!\n");
            return NULL;
        }
    }
}

int main()
{
    //test cases
    char b[]="fasdg";
    char c[]="Hello, mom and dad, how is it going?";
    char d[]="Hello , mom and dad, how is it going?";//the single comma won't be returned
                                                     //as a palindrom       

    char* result=findlong(c);
    if (result)
        printf("%s\n",result);

    return 0;
}
于 2012-07-27T06:40:55.110 回答
0

逐字获取,如果相等,则仅查看第一个和最后一个字符,然后继续进一步验证,否则继续下一个单词。

main()
{
   string  a =  "Hello mom and dad, how is it going?";
   printf("first_palindrome word = %s",first_palindrome(a));
}

char * first_palindrome(string abc)
{

  for(i=0;i<number_of_words;i++)
  { 
    write logic will send word by  word...
    if(palindrome(word))
    {
       return word;
    }
  }
 return "no_word_found";
}
于 2012-07-27T04:51:10.590 回答
0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int isPalindrome(const char *str){
    const char *front, *back;
    front=str;
    back =str + strlen(str)-1;
    for(;front<back;++front,--back){
        while(!isalpha(*front))++front;//isalnum?
        while(!isalpha(*back))--back;
        if(front > back || tolower(*front)!=tolower(*back))
            return 0;
    }
    return 1;
}

int main(){
    const char *data="Hello mom and dad, how is it going?";
    char *p, *src;
    p=src=strdup(data);
    for(;NULL!=(p=strtok(p, " \t\n,.!?"));p=NULL){
        if(isPalindrome(p)){
            printf("%s\n", p);
            break;
        }
    }
    free(src);
    return 0;
}
于 2012-07-27T10:01:37.960 回答