Valid Parentheses
题目:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
分析:
看到题目想到用stack,但是别忘了结尾要判断myStack.isEmpty()
解法:
public class Solution {
/**
* @param s A string
* @return whether the string is a valid parentheses
*/
public boolean parenMatched(char lhs, char rhs) {
if (rhs == ')') {
return lhs == '(';
} else if (rhs == ']') {
return lhs == '[';
} else {
return lhs == '{';
}
}
public boolean isValidParentheses(String s) {
// Write your code here
Stack<Character> myStack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char curr = s.charAt(i);
if (curr == '(' || curr == '[' || curr == '{') {
myStack.push(curr);
} else {
if (myStack.empty() ) {
return false;
} else {
if (!parenMatched(myStack.pop(),curr ) ) {
return false;
}
}
}
}
return myStack.empty();
}
}