棧--判斷迴文字串
阿新 • • 發佈:2019-01-02
棧–判斷迴文字串
思路
將字串的前半部分依次壓棧,再依次出棧後和字串後半部分一一比較。
程式碼
#include <stdio.h>
#include <string.h>
#define LEN 8
int main()
{
char a[LEN] = "abcddcba";
char s[LEN];
int i, len, mid, next, top;
len = LEN;
mid = len/2;
if (len%2 == 0) {
next = mid;
} else {
next = mid + 1;
}
top = 0;
for (i = 0; i < mid; i++) {
s[++top] = a[i];
}
for (i = next; i < len; i++) {
if (a[i] != s[top]){
break;
}
top--;
}
if (top == 0) {
printf("YES");
} else {
printf("NO");
}
return 0 ;
}