[LeetCode] 020. Valid Parentheses (Easy) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github:
https://github.com/illuz/leetcode


020.Valid_Parentheses (Easy)

链接

题目:https://oj.leetcode.com/problems/valid-parentheses/
代码(github):https://github.com/illuz/leetcode

题意

判断1个括号字符串是不是是有效的。

分析

直接用栈摹拟,很简单的。
Java 的括号匹配可以用 if 写,也能够用 HashMap<Character, Character> 存,还可以用 "(){}[]".indexOf(s.substring(i, i + 1)。 (这个讨论也能够用于 C++ 和 Python)

这里的 C++ 是用 if 匹配, Java 用 indexOf, Python 用 dict。

代码

C++:

class Solution {
public:
bool isValid(string s) {
stack<char> stk;
int len = s.length();
for (int i = 0; i < len; i++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
stk.push(s[i]);
} else {
if (stk.empty())
return false;
if (stk.top() == '(' && s[i] == ')')
stk.pop();
else if (stk.top() == '[' && s[i] == ']')
stk.pop();
else if (stk.top() == '{' && s[i] == '}')
stk.pop();
else
return false;
}
}
return stk.empty();
}
};

Java:

public class Solution {

public boolean isValid(String s) {
Stack<Integer> stk = new Stack<Integer>();
for (int i = 0; i < s.length(); ++i) {
int pos = "(){}[]".indexOf(s.substring(i, i + 1));
if (pos % 2 == 1) {
if (stk.isEmpty() || stk.pop() != pos – 1)
return false;
} else {
stk.push(pos);
}
}
return stk.isEmpty();
}
}

Python:

class Solution:
# @return a boolean
def isValid(self, s):
mp = {')': '(', ']': '[', '}': '{'}
stk = []
for ch in s:
if ch in '([{':
stk.append(ch)
else:
if not stk or mp[ch] != stk.pop():
return False
return not stk

波比源码 – 精品源码模版分享 | www.bobi11.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 本站源码并不保证全部能正常使用,仅供有技术基础的人学习研究,请谨慎下载
8. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!

波比源码 » [LeetCode] 020. Valid Parentheses (Easy) (C++/Java/Python)
赞助VIP 享更多特权,建议使用 QQ 登录
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡