Valid Parentheses

Given a String that only contains '(', ')', '[', ']' , '{', '}', determine if these parentheses are valid.

"()" "[]" "{}" are valid while "[}" "(}" and such pairs like that are not valid.

Solution:

1. We can use a Stack to solve this problem. Whenever we encounter a left parenthese, we push it to the stack. When ever we encounter a right parenthese, if the stack is empty or this cannot match the parenthese we pop from the stack,  just return false.

2. After scanning the whole string, if the stack is still not empty, just return false.

Code:

public class Solution {
    public boolean isValid(String s) {
    Stack<Character> st = new Stack<>();
    for(int i = 0; i < s.length(); i++){
        char temp = s.charAt(i);
        if(temp=='(' || temp=='[' || temp=='{')
            st.push(temp);
        else{
            if(st.empty())
                return false;
            char c = st.pop();
            if(c=='('&&temp!=')' || c=='['&&temp!=']' || c=='{'&&temp!='}')
                return false;
        }
    }
    if(!st.empty())
        return false;
    return true;
    }
}
View Code

 

posted @ 2017-06-22 02:37  小风约定  阅读(104)  评论(0)    收藏  举报