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.
//Create the Stack instance and add a couple of elements to it
Stack stack = new Stack();
String s1 = "element 1";
String s2 = "element 2";
stack.push(s1);
stack.push(s2);
System.out.println(stack.peek());
//element 2
//Find position of a certain element
int pos = stack.search("element 1");
System.out.println(pos);
//2
System.out.println(stack.pop());
System.out.println(stack.pop());
//element 2
//element 1
System.out.println(stack.empty());
//true
參考代碼:
Java
public class Solution {
public boolean isValid(String s) {
if(s==null || s.length()==0)
return false;
Stack<Character> parentheses = new Stack<Character>();
for (int i = 0; i< s.length(); i++){
char c = s.charAt(i);
if(c=='(' || c=='[' || c =='{')
parentheses.push(c);
else{
if (parentheses.empty())
return false;
if (c == ')' && parentheses.peek() != '(')
return false;
if (c == ']' && parentheses.peek() !='[')
return false;
if (c == '}' && parentheses.peek() !='{')
return false;
parentheses.pop();
}
}
return parentheses.empty();
}
}