一个单词是否属于回文的程序

问题描述 投票:0回答:1

写了一些算法来找出给定的单词是否是回文。但是当我调试时,我的一个变量(counter)似乎没有更新,并且我无法弄清楚它出了什么问题。不过我可能是错的...将需要任何帮助,因为我想盲目在线复制一些代码。下面是代码:

#include <iostream>
#include <cstring>


using namespace std;

int main(){
    //take input
    string input;
    cout << "Enter your word: ";
    cin >> input;

    //initialize arrays and variables
    int counter = 0, k = 0;
    int char_length = input.length();
    char characters[char_length];
    strcpy(characters, input.c_str());//copy the string into char array

    //index of character at the midpoint of the character array
    int middle = (char_length-1)/2;
    int booleans[middle]; //to keep 1's and 0's

    //check the characters
    int m = 0, n = char_length-1;
    while(m < middle && n > middle){
        if(characters[m] == characters[n]){
                booleans[k] = 1;
            } else {
                booleans[k] = 0;
            }
            k++;
            m++;
            n--;
    }

    //count number of 1's (true for being equal) in the booleans array
    for(int i = 0; i < sizeof(booleans)/sizeof(booleans[0])-1; i++){
        counter += booleans[i];
    }

    //compare 1's with size of array
    if(counter == middle){
        cout << input << " is a Palindrome!" << endl;
    } else {
        cout << input << " is not a Palindrome!" << endl;
    }

    return 0;
}
arrays algorithm variables palindrome
1个回答
0
投票

兄弟,似乎很难理解您的问题是什么以及您正在键入什么代码。我不是非常有经验,但是根据我的说法,回文是一个非常非常简单和容易的程序,我会把它写成:

#include <iostream>
#include <string.h>
using namespace std;
int main()
{
    char str1[20], str2[20];
    int i, j, len = 0, flag = 0;
    cout << "Enter the string : ";
    gets(str1);
    len = strlen(str1) - 1;
    for (i = len, j = 0; i >= 0 ; i--, j++)
        str2[j] = str1[i];
    if (strcmp(str1, str2))
        flag = 1;
    if (flag == 1)
        cout << str1 << " is not a palindrome";
    else
        cout << str1 << " is a palindrome";
    return 0;
}

在您可以尝试的每种情况下都可以使用。

© www.soinside.com 2019 - 2024. All rights reserved.