列表

详情


OR104. 括号配对问题

描述

括号配对问题

输入描述

给定一个字符串S,请检查该字符串的括号是否配对,只含有"[", "]", "(", ")"

输出描述

配对,返回true

不配对,返回false

示例1

输入:

abcd(])[efg

输出:

false

原站题解

C 解法, 执行用时: 2ms, 内存消耗: 224KB, 提交时间: 2019-08-11

#include <stdio.h>
#include <stdlib.h>
#define N sizeof(char)

int main()
{
	int front1 = 0, front2 = 0, behind1 = 0, behind2 = 0, count = 0;
	char ch;
	char *str = (char*)malloc(N);
	while ((ch = getchar()) != '\n')
	{
		if (ch == '(' || ch == '[')
		{
			str = (char*)realloc(str, N*(count + 1));
			str[count++] = ch;
			if (ch == '(')
				front1++;
			else if (ch == '[')
				front2++;
		}
		if (ch == ')' || ch == ']')
		{
			if (count == 0)
			{
				printf("false\n");
				return 0;
			}
			if (ch == ')' && str[count - 1] == '(')
			{
				behind1++;
				count--;
			}
			else if (ch == ']' && str[count - 1] == '[')
			{
				behind2++;
				count--;
			}
			if (behind1 > front1 || behind2 > front2)
			{
				printf("false\n");
				return 0;
			}
		}
	}
	if (behind1 == front1 && behind2 == front2)
		printf("true\n");
	else
		printf("false\n");
    free(str);
	return 0;
}

C 解法, 执行用时: 2ms, 内存消耗: 292KB, 提交时间: 2019-11-03

#include <stdio.h>
#include <string.h>
#define FALSE -1
#define TRUE 1
 
int judge(char s[100000], int len){
    int i, top;
     
    char stack[100000];
    top = 0;
    i = 0;
    for(   i=0;i<len;i++)
      {
         switch(s[i]){
             case '(':
                 stack[top] = s[i];
                 top ++;
                 break;
             
             case '[':
                 stack[top] = s[i];
                 top ++;
                 break;
             
             case ')':
             if(stack[ top - 1 ] == '('){
                  top --;
                  break;
             }else{
                return 0;
             }
             
            case ']':
               if(stack[ top - 1 ] == '['){
                  top --;
                  break;
               }else{
                  return 0;
               }
             
            default:
                break;
         }
    }
    if(top == 0) return 1;
    else return 0;
}
 
int main(){
    char s[100000];
    int len, i, j;
     
    scanf("%s",s);
    len = strlen(s);
     
    j = judge(s,len);
    if(j == TRUE) printf("true\n");
    else printf("false\n");
     
    return 0;
}

上一题