Saturday, January 14, 2017

Check Valid Parentheses

Given a string only with '(' and ')'. If it is a valid parentheses string, return the number of valid parentheses pairs. One '(' and one ')' is one pair. Otherwise, return -1. 

import java.util.*;

public class Solution {
    public static int validParentheses(String word) {
        if (word == null || word.length() == 0) {
            return 0;
        }
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < word.length(); i++) {
            if (word.charAt(i) == '(') {
                stack.push('(');
            } else if (word.charAt(i) == ')') {
                if (stack.isEmpty() || stack.pop() != '(') {
                    return -1;
                } 
            } else {
                return -1;
            }
        }
        if (!stack.isEmpty()) {
            return -1;
        }
        return word.length() / 2;
    }

    public static void main(String[] args) {
        int res = validParentheses("(())");
        System.out.println(res);
    }
}

No comments:

Post a Comment