Leetcode 20. Valid Parentheses

题目

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

分析

分析字符串中的括号字符是否匹配,用栈的思想就能完成,依次堆栈,遇到匹配的就出栈,最后所有的都匹配就证明正确,否则返回错误。

bool isValid(char* s) {
    bool ans=true;
    char * temp=(char *)malloc(sizeof(char)*10000);
    int templength=0;
    int slength=0;
    while(s[slength]!='\0'&& ans==true)
    {
        if(templength==0|| 
        (templength!=0&&(s[slength]=='('||s[slength]=='['||s[slength]=='{')))
        {
            temp[templength]=s[slength];
            templength++;
        }
        else if(  (temp[templength-1]=='('&&s[slength]==')') || 
                  (temp[templength-1]=='['&&s[slength]==']') ||
                  (temp[templength-1]=='{'&&s[slength]=='}'))
        {
            templength--;
        }
        else
        {
            ans=false;
        }
        slength++;
    }
    if(templength!=0)
        ans=false;
    return ans;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容