UVA401 Palindromes

问题描述:

输入一串字符判断它是否为回文串,镜像串。

Character Reverse Character Reverse Character Reverse
A A M M Y Y
B   N   Z 5
C   O O 1 1
D   P   2 S
E 3 Q   3 E
F   R   4  
G   S 2 5 Z
H H T T 6  
I I U U 7  
J L V V 8 8
K   W W 9  
L J X X    

 

 

 

输入:

每行输入一串字符

 

输出:

STRING CRITERIA
" -- is not a palindrome." if the string is not a palindrome and is not a mirrored string
" -- is a regular palindrome." if the string is a palindrome and is not a mirrored string
" -- is a mirrored string." if the string is not a palindrome and is a mirrored string
" -- is a mirrored palindrome." if the string is a palindrome and is a mirrored string

 

解题思路:

判断回文只要将两端的字符对比即可

回文只要将镜像表存入数组,在两端比对即可

 

AC:

#include "iostream"
#include "cstdio"
#include "cctype"
#include "cstring"

using namespace std;

const int MAX_N = 10000;
char s[MAX_N];
int len;

const char rev[] = "A   3  HIL JM O   2TUVWXY51SE Z  8 ";
                    
bool isPalindromes(char s[])
{
    for(int i = 0; i < (len + 1) / 2; i++)
    {
        if(s[i] != s[len - 1 - i])
        {
            return false;
        }
    }
    return true;
}

char change(char c)
{
    if(isalpha(c)) return rev[c - 'A'];
    return rev[c - '0' + 25];
}

bool isMirrored(char s[])
{
    for(int i = 0; i < (len + 1) / 2; i++)
    {
        if(change(s[i]) != s[len - 1 - i])
        {
            return false;
        }
    }
    return true;
}


int main(int argc, char const *argv[])
{
    while(scanf("%s", s) != EOF)
    {
        len = strlen(s);
        bool palindromes = isPalindromes(s);
        bool mirrored = isMirrored(s);

        if(mirrored && !palindromes) printf("%s -- is a mirrored string.\n\n", s);
        else if(!mirrored && palindromes) printf("%s -- is a regular palindrome.\n\n", s);
        else if(mirrored && palindromes) printf("%s -- is a mirrored palindrome.\n\n", s);
        else printf("%s -- is not a palindrome.\n\n", s);
    }
    return 0;
}

 

 

总结:

利用数组存储了字符到镜像字符的映射。

 

posted @ 2015-12-01 14:17  小图书馆  阅读(58)  评论(0)    收藏  举报