任务描述
本关任务:基于栈stack
数据结构判断字符串是否为“回文串”。
相关知识
为了完成本关任务,你需要掌握:1.如何创建一个栈,2.入栈、出栈操作,3.“回文串”概念。
- 创建栈、入栈和出栈操作请参考
第1关
回文串
简单来说,“回文串”是一个正读和反读都一样的字符串: noon
是回文串 moon
不是回文串
编程要求
本关的编程任务是补全右侧代码片段Palindrome
中Begin
至End
中间的代码,具体要求如下:
- 在
Palindrome
中,利用栈stack
判断字符串是否为回文串, 若是回文串输出YES
,否则输出NO
,末尾换行。
测试说明
平台将自动编译补全后的代码,并生成若干组测试数据,接着根据程序的输出判断程序是否正确。
以下是平台的测试样例:
样例一: 测试输入: 4
1221
预期输出: YES
样例二: 测试输入: 7
abababa
预期输出: YES
#include "stack_.h"
// 栈表操作实现文件
//
Stack* Stack_Create(int maxlen)
// 创建栈
{
Stack* stk = (Stack*)malloc(sizeof(Stack));
stk->data = (T*)malloc(sizeof(T)*maxlen);
stk->max = maxlen;
stk->top = -1;
return stk;
}
void Stack_Free(Stack* stk)
// 释放栈
{
free(stk->data);
free(stk);
}
void Stack_MakeEmpty(Stack* stk)
// 置为空栈
{
stk->top = -1;
}
bool Stack_IsEmpty(Stack* stk)
// 判断栈是否空
{
return -1 == stk->top;
}
bool Stack_IsFull(Stack* stk)
// 判断栈是否满
{
return stk->top == stk->max-1;
}
T Stack_Top(Stack* stk)
// 获取当前栈顶元素
{
return stk->data[stk->top];
}
T Stack_Push(Stack* stk, T e)
// 将元素e压入栈顶
// 返回栈顶点元素
{
if(Stack_IsFull(stk)) {
printf("Stack_IsFull(): stack full error when push element to the stack!\n");
Stack_Free(stk);
exit(0);
}
else{
stk->top += 1;
stk->data[stk->top] = e;
return Stack_Top(stk);
}
}
T Stack_Pop(Stack* stk)
// 将栈顶元素出栈
// 返回栈顶元素
{
if(Stack_IsEmpty(stk)) {
printf("Stack_IsEmpty(): stack empty error when pop element of the stack top!\n");
Stack_Free(stk);
exit(0);
}
else{
T topE = Stack_Top(stk);
stk->top -= 1;
return topE;
}
}
void Stack_Print(Stack* stk)
// 打印栈顶到栈低的元素
{
if (Stack_IsEmpty(stk)) {
printf("The stack is empty.\n");
return;
}
//printf("The stack contains: ");
for (int i=stk->top; i>=0; i--) {
printf("%d", stk->data[i]);
}
printf("\n");
}
void Palindrome(T* str, int len)
// 利用stack栈判断字符串是否为回文串
// 输入参数:字符串序列,字符串长度
// 若是回文串输出YES,否则输出NO,末尾换行
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
if (len==1) {
printf("%s\n", "YES");
}else{
Stack* stk=Stack_Create(132);
int mid =len/2;
for(int i=0;i<mid;i++)
Stack_Push(stk,str[i]);
if(len%2!=0) mid=mid+1;
for(int j=mid;j<len;j++)
{
T a=Stack_Top(stk);
if(str[j]!=a)
{
printf("%s\n", "NO");
break;
}else
Stack_Pop(stk);
}
if(Stack_IsEmpty(stk))
printf("%s\n", "YES");
}
/********** End **********/
}