簡體   English   中英

如何獲取字符串中單詞的相關回文長度?

[英]How to get the length of the relevant palindrome of a word in a string?

我需要獲取字符串中單詞的回文長度。 前任。 我的ot長度 =2。 我寫了以下代碼,但它不起作用。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {

    char str[20] = "tomyot";
    char rstr[20];
    strcpy(rstr, str);
    strrev(rstr);
    int i,j;
    int count = 0;
    int s=0;

    for(i=0;i<strlen(str); i++){

        for(j=s;j<strlen(str); j++){
            if(str[i] == rstr[j]){
                count+=1;
                s = j+1;
                continue;
            }

        }   

    }
    printf("%d",count);


    return 0;
}

代替

sizeof(str)

strlen(str)

前一個返回str數組的大小,即20 ,后一個返回str內容的長度,即6

我已經進行了更改並在/*.. */塊中的代碼中添加了注釋:

#include <stdio.h>
#include <string.h>

int main(void) {
    /*
      - You don't need to compute the reverse of the string, the input string itself will do your work.
      - strrev() is not supported in GCC, so don't use it. See https://stackoverflow.com/a/8534275/4688321
        for alternative implementation
     */
    char str[20] = "tomyot";
    int len_str = strlen(str);
    int i, j, cnt = 0;
    /*
     - You don't need two nested for loops, one loop with two pointers:
       first from the start of string and other from end of the string will do
     - Just compare the ith character (from start) with the jth character (from end)
     - Stop wherever i and j cross each other i.e. when i > j
     */
    for (i = 0, j = len_str - 1; i <= j && i < len_str - 1; i++, j--) {
        if (str[i] == str[j]) {
            cnt++;
        }
        else break;
    }
    printf("%d\n", cnt);
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM