欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

杭电oj1318(Palindromes)

程序员文章站 2022-04-01 17:21:12
...

杭电oj1318(Palindromes)

题目描述

输入一串字符,判断是否为回文数或者镜像字符串

Sample Input

NOTAPALINDROME
ISAPALINILAPASI
2A3MEAS
ATOYOTA

Sample Output

NOTAPALINDROME – is not a palindrome.

ISAPALINILAPASI – is a regular palindrome.

2A3MEAS – is a mirrored string.

ATOYOTA – is a mirrored palindrome.

答案

简单题~
题目明确说了不会输入非法字符,而且0是非法的
剩下的就是判断回文和镜像了

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

using namespace std;

void converse(char *);
bool is_palindrome(char *);
bool is_mirror(char *);

int main() {
	
	char str[50];
	bool palindrome, mirror;
	while (cin >> str) {

		/*Judge*/
		palindrome = is_palindrome(str);
		mirror = is_mirror(str);

		/*Output*/
		if (palindrome && mirror)
			printf("%s -- is a mirrored palindrome.\n", str);
		else if (palindrome)
			printf("%s -- is a regular palindrome.\n", str);
		else if (mirror)
			printf("%s -- is a mirrored string.\n", str);
		else
			printf("%s -- is not a palindrome.\n", str);
		printf("\n");
	}
}

void converse(char *str) {
	char *p = str, *q, tmp;
	for (q = str; *q != '\0'; q++)
		;
	q--;
	for (; p < q; p++, q--)
		tmp = *p, *p = *q, *q = tmp;
}

bool is_palindrome(char *str) {
	int len = strlen(str);
	char *reverse = new char[len + 1];
	strcpy_s(reverse, len + 1, str);
	converse(reverse);
	return !strcmp(str, reverse);
}

char reverse_char(char ch) {
	switch (ch) {
	case 'A':case 'H':case 'I':case 'M':
	case 'O':case 'T':case 'U':case 'V':
	case 'W':case 'X':case 'Y':case '1':case '8':
		return ch;
	case 'E':
		return '3';
	case 'J':
		return 'L';
	case 'L':
		return 'J';
	case 'S':
		return '2';
	case 'Z':
		return '5';
	case '2':
		return 'S';
	case '3':
		return 'E';
	case '5':
		return 'Z';
	default:
		return '\0';
	}
}

bool is_mirror(char *str) {
	int i, j;

	for (i = 0, j = strlen(str) - 1; i <= j; i++, j--) //注意是 i <= j
		if (str[i] != reverse_char(str[j])) {
			return false;
		}
	return true;
}
相关标签: oj