Leetcode: 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.

分析: 遍历字符串,使用栈依次存储字符,遇到’0’,’]’,,’}’出栈进行判断。 注意:’(‘和’)’只差为1,’[‘和’]’只差为2,’{‘和’}’只差为2,这可以帮助我们判读左括号和右括号是否成对。 C++示例代码:

class Solution{public:bool isValid(string s){string::size_type length = s.length();//如果给定的字符个数为奇数,直接返回falseif (length % 2){return false;}stack<char> chstack;distance;for (size_t i = 0; i < length; i++){if (s[i] == ‘)’ || s[i] == ‘]’ || s[i] == ‘}’){if (chstack.empty()){return false;}else{top = chstack.top();chstack.pop();distance = s[i] – top;//判断previous和current是否匹配if (distance != 1 && distance != 2){return false;}}}else{chstack.push(s[i]);}}//栈为空返回true,否则肯定有不匹配的括号在栈中返回falsereturn chstack.empty() ? true : false;}};

C#示例代码:

public class Solution{(string s){if (s.Length % 2 == 1) return false;Stack<char> chstack = new Stack<char>();char top= ‘ ‘;int distance = 0;for (int i = 0; i < s.Length; i++){if (s[i] == ‘)’ || s[i] == ‘]’ || s[i] == ‘}’){if (chstack.Count == 0){return false;}else{top= chstack.Pop();distance = s[i] – top;if (distance != 1 && distance != 2){return false;}}}else{chstack.Push(s[i]);}}return chstack.Count == 0 ? true : false;}}

Python代码: Python代码我没有使用判读左括号和右括号距离的方法

:length = len(s)stack = []if length % 2 != 0:i in range(length):s[i] == ‘}’:if not stack::top = stack.pop()top == top == ‘}’ and s[i] != ‘}’::stack.append(s[i])if stack::return True

自己变得跟水晶一般透明,

Leetcode: Valid Parentheses

相关文章:

你感兴趣的文章:

标签云: