Java


  • 0
    J

    public boolean isValid(String s) {
    Stack st = new Stack();
    for (int i=0; i<s.length(); i++) {
    char c = s.charAt(i);
    if ( c == '(' || c == '{' || c == '[') {
    st.push(c);
    }
    if ( c == ')' || c == '}' || c == ']') {
    if (st.isEmpty()) {
    return false;
    }
    char c1 = (char) st.pop();
    if ( c == ')' && c1 != '(' ) {
    return false;
    }
    if ( c == '}' && c1 != '{' ) {
    return false;
    }
    if ( c == ']' && c1 != '[' ) {
    return false;
    }
    }
    }
    return st.isEmpty();
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.