需要将多少个字符添加到字符串以构成回文

时间:2014-09-25 17:18:19

标签: algorithm

我刚刚接受了TCS的采访,我的最后一个问题是编写一个算法来查找需要在字符串中添加多少个字符才能使其成为回文。我刚开始,但无法完成。什么是找到它的方法?

2 个答案:

答案 0 :(得分:3)

String palindrome = "helllllll";

char [] chars = palindrome.toCharArray();

for (int i = 0; i < chars.length; i++) {
    int j = 0;
    for (; j < chars.length - i; j++) {
        if (chars[i+j] != chars [chars.length - 1-j])
            break;
    }
    if (j == chars.length - i) {
        System.out.println (i);
        break;
    }
}

答案 1 :(得分:0)

正如Niklas所说:

Find the leftmost character in the right half of the string that is a potential "mirror point" of a palindrome. It induces the solution. Also consider even-length palindromes

作为解释您问题的示例代码,这会执行回文测试,然后反向打印出来,而不会显示“!”,“或”等字符。

我已经用标题标出了回答你问题的过程:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    //Variables and arrays
    int const index = 30;
    char Phrase[index];
    char Reverse[index];
    char* Palindrome = Reverse;
    int i, j;

    cout << "Please enter a sentence to be tested as a palindrome: ";
    cin.getline(Phrase, 30);
    int length = strlen(Phrase);

    bool test = true;

    for(i = 0, j = length-1; i < j; i++, j--) //Loops from zero to half of the string
    {
        if(test) // if it is a palindrome so far
        {
            while(!isalpha(Phrase[i]) && i < j) { i++; }
            while(!isalpha(Phrase[j]) && i < j) { j--; }

            if(Phrase[i] != Phrase[j]) //Check if the characters match
            {
                test = false;
            }

        }
        else
        {
            break;
        }
    }

    if(test)
    {
        cout << endl << "Phrase/Word is a Palindrome." << endl << endl;
        for(j = strlen(Phrase) - 1; j >= 0; Palindrome++, j--)
        {
            *Palindrome = Phrase[j];
        }
        cout << "The phrase and reverse statement is: " << Reverse << endl << endl;
    }
    else
    {
        cout << endl << "Phrase/Word is not a Palindrome." << endl << endl;
    }

    system("Pause");
    return 0;
}