20. Valid Parentheses
Posted real1587
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了20. Valid Parentheses相关的知识,希望对你有一定的参考价值。
Given a string containing just the characters ‘(‘
, ‘)‘
, ‘{‘
, ‘}‘
,‘[‘
and ‘]‘
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
题目需要我们判断是否是正确的括号使用,这道题有点类似镜像串。用一个pos变量记录每次是否是对应的()[]{},如果符合则减一,如果不符合就把pos变量一直加上去直到碰到符合的括号,最后如果能削减到0说明括号的使用正确,不能则说明不正确。
1 bool isValid(char* s) { 2 int pos = 0;//记录还没排除的括号 3 for(int i=0;s[i]!=‘