Java Valid Paranthesis


  • 0
    T

    public boolean isValid(String s) {

    	if (s == "")
    		return true; // empty string is technically valid
    	if (s.length() % 2 == 1)
    		return false; // odd length wont work
    
    	boolean valid = true;
    	Stack<Character> open = new Stack<>(); // close stack
    	Stack<Character> close = new Stack<>(); // open stack
    
    	for (int i = 0; i < s.length(); i++) {
    		if (s.charAt(i) == '(') {
    			open.push('(');
    			close.push(')');
    
    		}
    
    		else if (s.charAt(i) == '{') {
    			close.push('}');
    			open.push('{');
    		}
    
    		else if (s.charAt(i) == '[') {
    			close.push(']');
    			open.push('[');
    		}
    
    		else if (s.charAt(i) == ')') {
    			if (!close.isEmpty() && close.pop() == ')' && !open.isEmpty() && open.pop() == '(')
    				continue;
    
    			else {
    				valid = false;
    				break;
    			}
    		}
    
    		else if (s.charAt(i) == ']') {
    			if (!close.isEmpty() && close.pop() == ']' && !open.isEmpty() && open.pop() == '[')
    				continue;
    			else {
    				valid = false;
    				break;
    			}
    		}
    
    		else if (s.charAt(i) == '}') {
    			if (!close.isEmpty() && close.pop() == '}' && !open.isEmpty() && open.pop() == '{')
    				continue;
    			else {
    				valid = false;
    				break;
    			}
    		}
    
    	}
    
    	if (open.isEmpty() && close.isEmpty() && valid)
    		return true;
    	else
    		return valid;
    
    }

  • 0
    A

    class Solution {

    public boolean isValid(String s) {
    HashMap<Character, Character> map = new HashMap<Character, Character>();
    map.put('(', ')');
    map.put('[', ']');
    map.put('{', '}');
    
    Stack<Character> stack = new Stack<Character>();
    
    for (int i = 0; i < s.length(); i++) {
    	char curr = s.charAt(i);
    
    	if (map.keySet().contains(curr)) {
    		stack.push(curr);
    	} else if (map.values().contains(curr)) {
    		if (!stack.empty() && map.get(stack.peek()) == curr) {
    			stack.pop();
    		} else {
    			return false;
    		}
    	}
    }
    
    return stack.empty();
    }
    

    }


Log in to reply
 

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