3.2用棧判斷迴文字串
阿新 • • 發佈:2019-02-01
/* 演算法思想: 1.當字串的長度是偶數時,入棧的字元個數正好是整個字串的一半; 則在棧非空的情況下,依次將棧頂元素出棧,並和字串後半段的元素比較, 當棧頂元素和當前字串不相同,說明不是迴文串,返回false;反之, 將新的棧頂元素和下一個字元比較,直到棧為空時,說明是迴文串。 2.當字串的長度是奇數時,需要將中間的字元跳過;入棧的是中間字元前面的字元, 並將棧中的元素和中間字元後面的字元一次比較。操作同上。 */ int IsHuiWen2(SqStack &S,char str[]){ int len=strlen(str); int m=len/2; int i; char temp; for(i=0;i<m;i++){ Push(S,str[i]); } // char e; // Pop(S,e); // printf("%c",e); if(len%2==0){ while(!IsEmpty(S)){ char e; Pop(S,e); temp=e; if(temp!=str[i]){ return 0; }else{ i++; } } }else if(len%2!=0){ i=i+1; while(!IsEmpty(S)){ char e; Pop(S,e); temp=e; if(temp!=str[i]){ return 0; }else{ i++; } } } return 1; }
具體實現:
/* 判斷迴文字串:將字串的一般入棧,然後將棧頂元素和後一半的字串的字元相比較 若相同,則將棧頂元素出棧。當棧最後為空時,說明該字串是迴文字串。 */ #include<stdio.h> #include<String.h> #define MAX 100 //定義一個棧 typedef struct{ char *base; char *top; int stacksize; }SqStack; //初始化棧 int InitStack(SqStack &S){ S.base=new char[MAX]; if(!S.base){ return 0; } S.top=S.base; S.stacksize=MAX; return 1; } //判斷棧是否為空 int IsEmpty(SqStack &S){ if(S.top==S.base){ return 1;//棧空 }else{ return 0;//棧非空 } } //判斷棧是否滿 int IsFull(SqStack &S){ if(S.top-S.base==S.stacksize){ return 1;//棧滿 }else{ return 0;//棧空 } } //進棧 int Push(SqStack &S,char e){ if(IsFull(S)){ return 0;//棧滿,無法入棧 } *S.top++=e; return 1; } int Pop(SqStack &S,char &e){ if(IsEmpty(S)){ return 0;//棧空,無法出棧 } e=*--S.top; return 1; } /* 演算法思想: 1.當字串的長度是偶數時,入棧的字元個數正好是整個字串的一半; 則在棧非空的情況下,依次將棧頂元素出棧,並和字串後半段的元素比較, 當棧頂元素和當前字串不相同,說明不是迴文串,返回false;反之, 將新的棧頂元素和下一個字元比較,直到棧為空時,說明是迴文串。 2.當字串的長度是奇數時,需要將中間的字元跳過;入棧的是中間字元前面的字元, 並將棧中的元素和中間字元後面的字元一次比較。操作同上。 */ int IsHuiWen2(SqStack &S,char str[]){ int len=strlen(str); int m=len/2; int i; char temp; for(i=0;i<m;i++){ Push(S,str[i]); } // char e; // Pop(S,e); // printf("%c",e); if(len%2==0){ while(!IsEmpty(S)){ char e; Pop(S,e); temp=e; if(temp!=str[i]){ return 0; }else{ i++; } } }else if(len%2!=0){ i=i+1; while(!IsEmpty(S)){ char e; Pop(S,e); temp=e; if(temp!=str[i]){ return 0; }else{ i++; } } } return 1; } int main(){ SqStack S; if(InitStack(S)){ printf("初始化成功!\n"); }else{ printf("初始化失敗!\n"); } printf("請輸入字串:"); char str[20]; scanf("%s",str); if(IsHuiWen2(S,str)){ printf("是迴文串!\n"); }else{ printf("不是迴文串!\n"); } }