#i..._栈的csp例题">
当前位置:   article > 正文

栈的例题_栈的csp例题

栈的csp例题

试写一个算法,识别一次读入的一个以@为结束符的字符序列是否为形如‘序列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;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

标答 比人家繁琐很多 - -

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/796240
推荐阅读
相关标签
  

闽ICP备14008679号