zoukankan      html  css  js  c++  java
  • 算法竞赛入门经典ch3_ex7回文词

    输入一个字符串,判断它是否为回文串以及镜像串。 输入字符串保证不含数字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.

    疑问

    • 如何判断镜像字符串?

      用常量列表。镜像字符串是以列表的形式给出来的,没有公式。

    要点

    • 判断回文

      s[i] != s[len-i-1]

    • 判断镜像

    code

    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    //常量字符串,存在镜像列表,与大写字母列表的顺序是对应的
    const char* rev = "A   3  HIL JM O   2TUVWXY51SE Z  8 ";//一定要与列表对应,特别是空格
    const char* msg[] = { "not a palindrome", "a regular palindrome", "a mirrored string", "a mirrored palindrome" };
    
    //返回ch的镜像字符
    char r(char ch)
    {
        if (isalpha(ch)) // isalpha的文件头为#include <ctype.h>
        {
            return rev[ch - 'A']; // 如果是字母
        }
        else
        {
            return rev[ch - '0' + 25]; //如果是数字,返回镜像列表中对应的镜像
        }
    }
    
    int main()
    {
        char s[30];
        while (scanf("%s", s) == 1)
        {
            int len = strlen(s);
            int isPalindrome = 1, isMirroro = 1;
            for (int i = 0; i < (len + 1) / 2; i++)
            {
                if (s[i] != s[len-i-1])
                {
                    isPalindrome = 0;
                }
                if (r(s[i]) != s[len-i-1])
                {
                    isMirroro = 0;
                }
            }
            printf("%s -- is %s. 
    
    ", s, msg[2 * isMirroro + isPalindrome]);
        }
    
        return 0;
    }

    小结

    for(int i = 0; i < (len+1)/2; i++)

    为什么这里是(len+1)/2?如果只判断回文,不用加1;判断镜像需要加1,因为镜像即使在中间它的镜像字母不一定是它自己,比如S的镜像是2.

    • 输出,为什么是msg[2 * isMirroro + isPalindrome]

      最简单的方法是写if语句。这里用了一个列表,我很欣赏这种方法,用数组存,用数组的索引方式读。答案是这样存的,把它看作一个二维数组存在了一维数组里面:

      const char* msg[] = { "not a palindrome", "a regular palindrome", "a mirrored string", "a mirrored palindrome" };

      这样看就行了:

      所以是2m+p(先变的是p)。

    • isalpha

      判断字符是否为字母,类似的还有isdigit、isprint,在ctype.h中定义。toupper、tolower等工具可以用来转换大小写。

  • 相关阅读:
    linux___用户管理
    linux基础_vim命令
    linux
    linux_centos安装
    python基础1_哈希碰撞的认识
    oop对象,面向对象
    Oracle数据库—— 事务处理与并发控制
    Oracle数据库——索引、视图、序列和同义词的创建
    Oracle数据库——触发器的创建与应用
    Oracle数据库—— 存储过程与函数的创建
  • 原文地址:https://www.cnblogs.com/shanchuan/p/8150299.html
Copyright © 2011-2022 走看看