回文词

Posted Intro1997

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了回文词相关的知识,希望对你有一定的参考价值。

题目来自于刘汝佳的《算法竞赛入门经典(第二版)》

题目描述:
输入一个字符串,判断它是否为回文串以及镜像串。输入字符串保证不含数字0。所谓回文串,就是反转以后跟原串相同,如 abba 和 madam。所有镜像串,就是左右镜像之后和原串相同,如 2s 和 3AIAE。注意,并不是每个字符在镜像之后都能得到一个合法字符。在本题中,每个字符的镜像如图所示

  输入的每行包含一个字符串(保证只有上述字符,不含空白字符),判断它是否为回文串和镜像串(共四种组合)。每组数据之后输出一个空行。

  样例输入:

  NOTAPALINDROME

  ISAPALINILAPASI

  2A3MEAS

  ATOYOTA

  样例输出:
  NOTAPALINDROME -- is not a palindrome.

  ISAPALINILAPASI -- is a regular palindrome.

  2A3MEAS -- is a mirrored string.

  ATOYOTA -- is a mirrored palindrome.

我的代码:

#include<iostream>
#include<cstring>
#include<ctype.h>
using namespace std;

int main() {
    char a[100], chat[]="A   3  HIL J O   2TUVWX51SE Z  8 ";
    int i, j, note = 0, no = 0;
    while (cin >> a)
    {
        note = 0;
        for (i = 0; i < strlen(a) / 2; i++) 
        {
            if (a[i] == a[strlen(a) - 1 - i]) 
            {
                if (isalpha(a[i]) && chat[a[i] - 65] != a[strlen(a) - 1 - i])
                {
                    no = 1;
                    break;
                }
            }
            if (a[i] != a[strlen(a) - 1 - i])
            {
                if (isalpha(a[i]) && chat[a[i] - 65] != a[strlen(a) - 1 - i])
                {
                    no = 1;
                    break;
                }
                note = 1;
                break;
            }
        }
        if (note == 0 && no == 0)
        {
            cout << a << "-- is a mirrored palindrome.\\n";
            continue;
        }
        if (note == 1)
        {
            cout << a << " -- is not a palindrome.\\n";
            continue;
        }
        if (note == 0)
        {
            cout << a << " -- is a regular palindrome.\\n";
            continue;
        }
        if (no == 0)
        {
            cout << a << "-- is a mirrored string.\\n";
            continue;
        }
        if (no == 1)
        {
            cout << a << "-- is not a mirrored string.\\n";
            continue;
        }
    }
    return 0;
}

答案的代码:

#include<stdio.h>
#include<string.h>
#include<ctype.h>
const char* rev = "A   3  HIL J O   2TUVWX51SE Z  8 ";
const char* msg[] = { "not a palindrome", "a regular palindrome", "a mirrored string", "a mirrored palindrome" };
char r(char ch) {
    if (isalpha(ch)) return rev[ch - \'A\'];
    return rev[ch - \'0\' + 25];
}
int main() {
    char s[30];
    while (scanf("%s", s) == 1) {
        int len = strlen(s);
        int p = 1, m = 1;
        for (int i = 0; i < (len + 1) / 2; i++) {
            if (s[i] != s[len - 1 - i])p = 0;
            if (r(s[i]) != s[len - 1 - i]) m = 0;
        }
        printf("%s -- is %s.\\n\\n", s, msg[m * 2 + p]);
    }
    return 0;
}

 

以上是关于回文词的主要内容,如果未能解决你的问题,请参考以下文章

Vijos1327回文词

Vijos 1327回文词(DP)

回文词 (Palindromes,Uva401)

回文词

C++回文词

回文词(Palindromes, UVa401)