LeetCode_Easy心得:20. Valid Parentheses(C语言)

来源:互联网 发布:jquery1.72.min.js 编辑:程序博客网 时间:2024/05/29 17:46

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.

/** 题目分析:这是一个括号匹配问题,也是堆栈的经典问题。这一题需要我们判断输入的字符串括号是否匹配(输入字符串只包含'(', ')', '{', '}', '[' 和']'),例如:若输入字符串是"({})",则返回true(即括号匹配);若输入字符串是"({)}",则返回false(即括号不匹配)。  */

/** 代码思路:这一题代码用到了堆栈中的先进后出概念,①创建一个标志位flag=-1和一个空字符串stack;②从第一个字符开始读取输入字符串;③检查读入的字符,if{如果是'('或'{'或'[',则标志位加一,同时该括号存入stack;}else{如果是')'或'}'或']',则比较stack最后一次存入的字符,如果相匹配,则标志位减一,否则直接返回false;}; ④读取输入字符串的下一个字符,并且每读取一个字符,执行一次步骤③,直至输入字符串全部读取完毕;⑤最后检查标志位flag是否与初值相等,相等返回true,否则返回false。 */


bool isValid(char* s) {    char stack[1000000];    //空字符串stack;    int flag = -1;          //标志位flag;        while(*s){              //如果字符指针s的内容不为'\0',则执行循环;       if(')' == *s){       //以下三个if任意一个不满足,则括号不匹配,直接返回false;           if(flag>=0 && stack[flag--]=='(');           else return false;       }       else if(']' == *s){           if(flag>=0 && stack[flag--]=='[');           else return false;       }       else if('}' == *s){           if(flag>=0 && stack[flag--]=='{');           else return false;       }else{           stack[++flag] = *s;         }       s ++;    //指针s指向下一个字符空间;    }    return -1 == flag;  //如果标志位flag等于初值(即-1),则说明括号匹配,否则括号不匹配;}
// LeetCode运行时间:1ms±1ms;


阅读全文
1 0