试写一个算法,识别一次读入的一个以@为结束符的字符序列是否为形如‘序列1&序列2’模式的字
符序列。其中序列1 和序列2 中都不含字符‘&’,且序列2 是序列1 的逆序列。例如,‘a+b&b+a’是属该模
式的字符序列,而‘1+3&3-1’则不是。
我自己的实现
#include "../SqStack.h"
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main(){
char *str = "A+B&B-A@";
cout << str << endl;
char seq1[30];
char seq2[30];
int i = 0, j = 0;
while(str[i]!='&'){
seq1[i] = str[i];
i++;
}
seq1[i] = '\0';
i++;
while(str[i]!='@'){
seq2[j] = str[i];
i++;
j++;
}
seq2[j] = '\0';
cout << seq1 << endl << seq2 << endl;
SqStack S;
InitStack(S);
char inv_seq1[30];
i = 0;
while(seq1[i]){
Push(S, seq1[i++]);
}
i = 0;
while(!StackEmpty(S)){
Pop(S, inv_seq1[i++]);
}
inv_seq1[i] = '\0';
strcmp(inv_seq1, seq2) == 0 ? cout << "匹配" << endl : cout << "不匹配" << endl;
return 0;
}
标答 比人家繁琐很多 - -
BOOL Symmetry(char a[])
{
int i=0;
Stack s;
InitStack(s);
ElemType x;
while(a[i]!='&' && a[i]){
Push(s,a[i]);
i++;
}
if(a[i]) return FALSE;
i++;
while(a[i]){
Pop(s,x);
if(x!=a[i]){
DestroyStack(s);
return FALSE;
}
i++;
}
return TRUE;
}