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.
第一想法果断是用栈啊~~
java code
public class Solution {
public boolean isValid(String s) {
int length = s.length();
if(length == 0 || length%2 == 1) return false;
String record = "(){}[]";
Stack<Character> myStack = new Stack<Character>();
if(s.charAt(0) == '(' || s.charAt(0) == '{' || s.charAt(0) == '[') myStack.push(s.charAt(0));
else return false;
for(int i=1; i<length; i++) {
if(s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') myStack.push(s.charAt(i));
else {
int pos = record.indexOf(s.charAt(i));
if(record.charAt(pos-1) != myStack.peek()) return false;
else {
myStack.pop();
}
}
}
if (myStack.empty()) return true;
else return false;
}
}
243 ms
ruby code
# @param {String} s
# @return {Boolean}
def is_valid(s)
length = s.length
return false if (length == 0 || length%2 == 1)
left = ['(', '{', '[']
right = [')', '}', ']']
record = []
length.times do |i|
if left.include?(s[i])
record.push(s[i])
else
if(left[right.index(s[i])] != record[-1])
return false
else
record.pop
end
end
end
if record.empty?
return true
else
return false
end
end
76ms