OA原题描述参考:
注意:具体抽到的题目可能会有细微变化。
leetcode 20
解题思路参考:
用stack存括号,碰到对应括号就pop。
参考答案:
public class Solution {
/**
* @param s A string
* @return whether the string is a valid parentheses
*/
public boolean isValidParentheses(String s) {
// Write your code here
if (s == null || s.length() == 0) {
return true;
}
Stack<Character> stack = new Stack<>();
for (Character c : s.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else {
if (!stack.isEmpty() && isValid(stack.peek(), c)) {
//System.out.println(stack);
stack.pop();
} else {
return false;
}
}
}
return stack.isEmpty();
}
private boolean isValid(char a, char b) {
return (a == '[' && b == ']') ||
(a == '{' && b == '}') ||
(a == '(' && b == ')');
}
}