题目
地址:https://leetcode-cn.com/problems/valid-parentheses/
描述: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.
代码
class Solution {
public boolean isValid(String s) {
char[] arr = s.toCharArray();
int index = 0;
for (char ch: arr) {
char cur = getByChar(ch);
if (cur == ' ') {
arr[index++] = ch;
continue;
}
if (index < 1 || arr[index - 1] != cur){
return false;
}
index--;
}
return index == 0;
}
private char getByChar(char ch) {
switch(ch) {
case ')': return '(';
case '}': return '{';
case ']': return '[';
default: return ' ';
}
}
}