算法思想:代码是将字符串全部入栈,然后扫描字符串进行比较,直到扫描到字符串尾部,该算法需要两次扫描字符串,效率不高。
可以改进代码,只将字符串的前半部分入栈,然后前半部分出栈与字符串后半部分比较,算法思想类似模式判断,再此不再赘述,此代码只需扫描字符串一次,效率高。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define max_size 100
typedef char ElemType;
typedef struct SqStack {ElemType data[max_size];int top;
};
void initial(SqStack& S) {S.top = -1;
}
bool isEmpty(SqStack S) {if (S.top == -1)return true;return false;
}
//入栈
bool Push(SqStack& S, ElemType e) {if (S.top + 1 == max_size)return false;S.data[++S.top]=e;return true;
}
//出栈
bool Pop(SqStack& S, ElemType &e) {if (S.top == -1)return false;e = S.data[S.top--];return true;
}
bool getTop(SqStack S, ElemType& e) {if (S.top == -1)return false;e = S.data[S.top];return true;
}
bool judgePalindrome(char* str) {SqStack S;initial(S);char* pMove1 = str,*pMove2=str;while (*pMove1 != '\0') {Push(S, *pMove1++);}char c;while (*pMove2 != '\0') {Pop(S, c);if (c != *pMove2)return false;pMove2 += 1;}return true;}
int main() {char str[max_size] = { '\0' };scanf("%s", str);if (judgePalindrome(str)) {printf("yes");}else {printf("no");}return 0;
}