Judgment of palindrome sequence

content:

A palindrome is a character sequence that reads the same both forward and backward, such as "abba" and "abdba" are both palindromes, but "good" is not a palindrome. Try writing an algorithm to determine whether a given character vector is a palindrome.

step:

Analysis of Algorithms:

A palindrome sequence is a sequence whose forward reading and reverse reading are the same, that is, to compare a sequence and its reverse sequence, and the stack just has the characteristics of first in last out, positive sequence input and reverse sequence output, so we can use the stack to solve this problem.

We use an array stack to take half of the string to be judged and put it on the stack , and then pop it out of the stack , so that the first half of the output sequence is in reverse order , and we only need to compare it with the remaining characters that have not been pushed into the stack String sequences are compared, and if there is a one-to-one correspondence, it is a palindrome sequence.

code show as below:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Stack                                //定义数组栈
{
    int top;
    char str[100];
}STACK;
int main()
{
    int len,i,mid,next;
    char str[100];
    STACK s;
    s.top=0; 
    gets(str);                               //输入字符串 
    len=strlen(str);                           //求字符串的长度 
    mid=len/2;                              //取字符串中间位置 
    for(i=0;i<mid;i++)                         //一半字符串入栈 
    {
        s.str[s.top]=str[i];
        s.top++;
    }
    if(len%2!=0)     //字符串长度为奇数时,后半段字符串从中间位置+1开始 
    {
        next=mid+1;
    }else           //否则,后半段字符串从中间位置开始 
	{
        next=mid;
    }
    while(s.top!=0)
    {
        if(s.str[s.top-1]==str[next])//前半段的最后一个字符与后半段的第一个字符相等,继续比较 
        {
            s.top--;
            next++;
        }
        else
        {
            break;
        }
    }
    if(s.top==0)
    {
        printf("是回文\n");
    }
    else
    {
        printf("不是回文\n");
    }
    return 0;
}

operation result:

 

 

 

Guess you like

Origin blog.csdn.net/weixin_54474126/article/details/121784583