您的位置:首页 > 其它

回文字镜像字 (Palindromes, UVa401)

2017-01-13 21:16 405 查看


代码如下,练手用。

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

using namespace std;

//常量字符串进行替换和格式化输出消息非常的方便
const char* rev = "A   3  HIL JM O   2TUVWXY51SE Z  8 ";
const char* msg[] = { "is not a palindrom.", "is a regular palindrom.",
"is a mirrored string.", "is a mirrored palindrome." };

char mirr(char chr)
{
if (isalpha(chr))
{
return rev[chr - 'A'];
} else if (isdigit(chr) && chr != '0')
{
return rev[chr - '1' + 26];
} else
{
return chr;
}
}

int main()
{
char s[30];

while (scanf("%s", s) == 1)     //输入有空格,Tab分割的用scanf()方便
{
int len = strlen(s);
int ok_palindrom = 1, ok_mirrored = 1;

for (int i = 0; i <= (len - 1) / 2; i++)
{
if (s[i] != s[len - 1 - i])
{
ok_palindrom = 0;
}
if (s[i] != mirr(s[len - 1 - i]))
{
ok_mirrored = 0;
}
}

printf("%s -- %s", s, msg[ok_mirrored * 2 + ok_palindrom]);
//      也可以用此种简单方法格式化输出
//      if (!ok_palindrom && !ok_mirrored)
//          printf("%s -- is not a palindrome.\n\n", s);
//      if (ok_palindrom && !ok_mirrored)
//          printf("%s -- is a regular palindrome.\n\n", s);
//      if (!ok_palindrom && ok_mirrored)
//          printf("%s -- is a mirrored string.\n\n", s);
//      if (ok_palindrom && ok_mirrored)
//          printf("%s -- is a mirrored palindrome.\n\n", s);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: