Java solution with switch and int[]


  • 0
    K
    public class Solution {
        public boolean isValid(String s) {
            if(s == null || s.length() < 2 || s.equals("") || s.length()%2 != 0)return false;
            char[] c = s.toCharArray();
            int[] t = new int[c.length];
            int index = 0;
            for(int i = 0; i < c.length; i++){
            	if(check1(c[i]) > 0){
            		t[index++] = check1(c[i]);
            	}else if(check2(c[i]) > 0 && index > 0){
            		if(check2(c[i]) == t[index-1]){
            			index--;
            		}else{
            			return false;
            		}
            	}
            }
            if(index > 0){
            	return false;
            }
            return true;
        }
    
        int check1(char c){
            switch (c){
                case '(': return 1;
                case '{': return 2;
                case '[': return 3;
                default:return 0;
            }
        }
    
        int check2(char c){
            switch (c){
                case ')': return 1;
                case '}': return 2;
                case ']': return 3;
                default:return 0;
            }
        }
    
    }

Log in to reply
 

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