JD15. 括号匹配方案
描述
合法的括号匹配序列被定义为:输入描述
输入包括一行,一个合法的括号序列s,序列长度length.输出描述
输出一个整数,表示方案数示例1
输入:
(((())))
输出:
24
示例2
输入:
()()()
输出:
1
C 解法, 执行用时: 2ms, 内存消耗: 356KB, 提交时间: 2020-08-08
#include <stdio.h> int main(){ int lnum,sum,i; char str[50]={'\0'}; scanf("%s",str); lnum=0; sum=1; for (i=0;i<strlen(str);i++){ if (str[i]=='(') { lnum++; continue; } if (str[i]==')') { sum=sum*lnum; lnum--; } } printf("%d",sum); return 0; }
C 解法, 执行用时: 2ms, 内存消耗: 356KB, 提交时间: 2020-07-28
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #define MAX_SIZE 23 struct Stack{ char *base; int top; int size; }; void init_stack(struct Stack *s){ s->base = (char *)malloc(sizeof(char) * MAX_SIZE); s->top = -1; s->size = 0; } bool isEmpty(struct Stack *s){ if(s->top == -1) return true; else return false; } bool isFull(struct Stack *s){ if(s->top == MAX_SIZE) return true; else return false; } void push(struct Stack *s, char a){ if(isFull(s)) return; else{ s->base[++s->top] = a; s->size ++; } } char pop(struct Stack *s){ if(!isEmpty(s)){ char tmp = s->base[s->top--]; s->size --; return tmp; }else exit(-1); } void process(char *s, int size){ // int size = (int)strlen(s); struct Stack *stack = (struct Stack *)malloc(sizeof(struct Stack)); init_stack(stack); int count = 1; for(int i = 0; i < size; i ++){ if(s[i] == '(') push(stack, s[i]); else{ count *= stack->size; pop(stack); } } printf("%d", count); } int main(int argc, const char * argv[]) { // insert code here... char s[20]; scanf("%s", s); process(s, strlen(s)); return 0; }