The problems I have submitted so many times


  • 1
    K
    public int longestValidParentheses(String s) {
        if(s == null || s.isEmpty()) return 0;
        
        Stack<Integer> stack = new Stack<>();
        int count = 0;
        int len = s.length();
        int[] maxNum = new int[len];
        for(int i = 0;i<s.length();i++){
            char ch = s.charAt(i);
            if(stack.isEmpty() && ch == ')'){
            	maxNum[i] = 0;
            }else{
                if(ch == '('){	            	
                	stack.push(i);
                	maxNum[i] = 0;
                }else {	 
                	int j = stack.pop();
                    maxNum[i] = (i-j+1);
                }
            }
        }
        int max = 0;
        
        int index = len-1;
        count = 0;
        while(index >= 0){
        	if(maxNum[index] != 0){
        		count += maxNum[index];
        		index -= (maxNum[index]);
        	}else{
        		if(max < count){
        			max = count;
        		}
        		count = 0;
        		index--;
        	}
        }
        return max<count ? count:max;
    }

Log in to reply
 

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