leetcode 020-Valid Parentheses

problem:

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

example:

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Difficulty:Easy

hint:

  • 使用一个栈存储左括号,碰到输入的字符为右括号时则出栈,并比较两个括号是否匹配。
  • 所有字符比较完成后,栈应为空,表示所有括号都相对应。

code:

#include<stdio.h> 
#include<malloc.h>
#include<string.h>
//typedef int bool;
//#define true 1
//#define false 0
typedef enum {true=1, false=0} bool;
bool isValid(char* s){
    char* t = (char*)malloc(strlen(s)*sizeof(char));
    int i,j = 0;
    for(i = 0;i<strlen(s);i++){
        switch(s[i]){      //接受新的字符
        case '(': 
            t[j++] = ')';
            break;
        case '{':
            t[j++] = '}';
            break;
        case '[':
            t[j++] = ']';
            break;
        default:
            if(t[--j]!=s[i]){      //出栈并比较两个字符
                return false;
            }
            break;
        }
    }
    if(j!=0){
        return false;
    }
    return true;
}
int main(){
    bool f = isValid("(");
    printf("%d",f);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容