【算法】回文串&镜像串

回文串&镜像串

字符对应关系

A   3  HIL JM O   2TUVWXY51SE Z  8 (镜像字符)
ABCDEFGHIGKLMNOPQRSTUVWXYZ123456789(原字符)
镜像字符为空的地方,说明对应的原字符没有镜像字符
ABCDEFGHIGKLMNOPQRSTUVWXYZ123456789(原字符)
镜像字符为空的地方,说明对应的原字符没有镜像字符

样例输入:

NOTAPALINDROME

LSAPALINILAPASI

样例输出:

NOTAPALINDROME -- is not a palindrome.

LSAPALINILAPASI -- is not a palindrome.

镜像字符:


const char* rev = "A   3  HIL JM O   2TUVWXY51SE Z  8 ";const char* rev = "A   3  HIL JM O   2TUVWXY51SE Z  8 ";

返回镜像字符:


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

isalpha(int c)当c为英文字母a-z或A-Z时,返回非零值,否则返回零。相当于


if(c<='z' && c>='a' || c<='Z' && c>='A')if(c<='z' && c>='a' || c<='Z' && c>='A')

rev['A'-'A']值为'A'

rev['B'-'A']值为' '

rev['8'-'0'+25]值为'8'

主函数:


int main() {
  char s[30];
  while(scanf("%s", s) == 1) {
    int len = strlen(s);
    int p = 1, m = 1;   //状态,是回文串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]);
      /*
       *既不是回文串p=0,也不是镜像串m=0,m*2+p=0;
       *是回文串p=1,但不是镜像串m=0.m*2+p=1;
       *不是回文串p=0,但是镜像串m=1,m*2+p=2;
       *既是回文串p=1,又是镜像串m=1,m*2+p=3
      */
  }
  return 0;
}int main() {
  char s[30];
  while(scanf("%s", s) == 1) {
    int len = strlen(s);
    int p = 1, m = 1;   //状态,是回文串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]);
      /*
       *既不是回文串p=0,也不是镜像串m=0,m*2+p=0;
       *是回文串p=1,但不是镜像串m=0.m*2+p=1;
       *不是回文串p=0,但是镜像串m=1,m*2+p=2;
       *既是回文串p=1,又是镜像串m=1,m*2+p=3
      */
  }
  return 0;
}

结果:


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

 

猜你喜欢

转载自blog.csdn.net/HuaLingPiaoXue/article/details/80086292