2ms C++ solution


  • 0
    K
    class Solution {
    public:
        bool isValid(string s) {
            int index = -1;
    	    int a[s.length()];
    	    bool properClose = false;
    	    for (unsigned int i = 0; i < s.length(); i++) {
    		    if (isOpenChar(s[i])) {
    			    properClose = false;
    			    a[++index] = s[i];
    		    } else {
    			    if (index < 0) {
    				    properClose = false;
    				    break;
    			    } else {
    				    if (s[i] == getClosedChar((char) a[index])) {
    					    properClose = true;
    					    index--;
    				    } else {
    					    properClose = false;
    					    break;
    				    }
    			    }
    		    }
    	    }
    	    if (index >= 0)
    		    properClose = false;
    	    return properClose;
            }
        
            char getClosedChar(char openChar) {
        	char result = '\0';
    	    switch (openChar) {
    		    case '(':
    			    result = ')';
    			    break;
        		case '[':
    	    		result = ']';
    		    	break;
        		case '{':
    	    		result = '}';
    		    	break;
        		default:
    	    		cerr << "Error: Unkown character passed into function." << endl;
    		    	break;
    	    }
    	    return result;
        }
    
        bool isOpenChar(char c) {
    	    bool result = false;
    	    switch (c) {
    		    case '(':
    		    case '[':
    		    case '{':
    			    result = true;
    			    break;
    		    default:
    			    result = false;
    			    break;
    	    }
    	    return result;
        }
    };

Log in to reply
 

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