C++ solution 0ms


  • 0
    public:
        bool isValid(string s)
        {
            int n = s.size();
            if(n == 0)
                return true;
            if(n % 2)
                return false;
            
            int i = 0;
            stack<char> str;
            str.push(s.at(i++));
            char currentChar = ' ';
    
            while(i < n)
            {
                currentChar = s.at(i++);
                if(currentChar == '(' || currentChar == '{' || currentChar =='[' )
                    str.push(currentChar);
                else
                    if( (str.top() == '{' && currentChar == '}') || (str.top() == '[' && currentChar == ']') || (str.top() == '(' && currentChar == ')'))
                        str.pop();
                    else
                        return false;
            }
            return (str.size())?false:true;
        }

  • 0
    S
    public class Solution {
        public boolean isValid(String s) {
            Map<Character, Character> map = new HashMap<>();
            map.put('}', '{');
            map.put(']', '[');
            map.put(')', '(');
            Set<Character> openSet = new HashSet<>();
            openSet.add('{');
            openSet.add('(');
            openSet.add('[');
            
    		Stack stack = new Stack();
    		
    		for(int i = 0; i < s.length(); i++){
    			if(openSet.contains(s.charAt(i))){
    				stack.push(s.charAt(i));
    			}
    			else if(stack.empty()){
    			    return false;
    			}
    			else{
    				if(map.get(s.charAt(i)) != (char)stack.pop()) return false;
    			}
    		}
    		
    		if(stack.empty()){
    		    return true;
    		}
    		else return false;
        }
    }

Log in to reply
 

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