leetcode-20. Valid Parentheses 有效的括号 (C) 华为一面
leetcode 20. Valid Parentheses
华为base杭州通开一面题目
Given a string s 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. Example 1: Input: s = "()" Output: true Example 2: Input: s = "()[]{}" Output: true Example 3: Input: s = "(]" Output: false Example 4: Input: s = "([)]" Output: false Example 5: Input: s = "{[]}" Output: true
思路
使用栈后进先出的性质。 我们需要知道的是,该题要求的几个条件:
-
brackets 类型和顺序要对应 比如{[]}是legal的但是{[]}]就是illegal的。 一定要有左右bracket,右bracket做结尾。 长度必须2的倍数
遍历一次string,把左括号都存进stack. 按照题中legal string的定义,那当我们遇到第一个右符号我们就需要判断栈中最后一个进的左括号,也就是栈最顶部的是否符合这个右括号。如果不符合,那就是false; 如果符合,把这个符合pop出来,或者把栈的长度减1,减去这个元素。
以此类推遍历整个string。
time complexity: O(n)
Space Complexity: O(n)
char pair(char a){ if (a == }) return {; if (a == ]) return [; if (a == )) return (; if (a == >) return <; return 0; } bool isValid(char * s){ int n = strlen(s); //the length has to be multiple of 2 if (n % 2 == 1) { return false; } int stack[n+1]; int top = 0; for (int i = 0; i<n; i++){ //iterate the string char ch = pair(s[i]); //recognize the right brackets if (ch){ if (top == 0 || stack [top - 1] != ch){ return false; } top--; }else //Recognize the left brackets and put in the stack //push in the stack { stack[top++] = s[i]; } } return top == 0; }