Leetcode20. Effective brackets

Title Description

Includes only a given (,), {,}, [,] the string, the string is determined whether or not valid.

Valid string to be fulfilled: the left bracket must be of the same type of closed right parenthesis. Left parenthesis must be closed in the correct order. Note the empty string can be considered a valid string.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "(]"
Output: false

answer

There are two main topics of this solution, Violence Act and stack method.

Stack method (java)

Ideas: When faced with a problem have recently relevance, consider using a stack to solve the problem. But the same is stack to solve, can be implemented on a variety of specific ways. In the following manner using this idea: encounters left parenthesis, right parenthesis corresponding put onto the stack. Encounter a right parenthesis on top of the stack with the current comparison.


class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for (char c : s.toCharArray()) {
            if (c == '(') stack.push(')');
            else if (c == '[') stack.push(']');
            else if (c == '{') stack.push('}');
            else if (stack.isEmpty() || stack.pop() != c) return false;
        }
        return stack.isEmpty();
        
    }
}

Complexity Analysis

  • Time complexity: O (n)
  • Space complexity: O (n)

Violence Act (java)

Idea: replace the idea, as if lianliankan. N sequences make the most of the cycles, which can find a matching left and right parentheses, and then replace the original brackets around "" is actually deleted. Circulation in the end, if there is no sign of leaving the match, it returns False.

class Solution {
	public boolean isValid(String s) {
		if(s==null || "".equals(s)) {
			return true;
		}
        
		while(s.contains("()") || s.contains("[]") || s.contains("{}")) {
		
			if(s.contains("()")) {
				s = s.replaceAll("\\(\\)","");
			}
	
			if(s.contains("[]")) {
				s = s.replaceAll("\\[\\]","");
			}
			if(s.contains("{}")) {
				s = s.replaceAll("\\{\\}","");
			}
		}
		
		return "".equals(s)? true : false;
	}
}
  • Time complexity: O ( n 2 n^2 )
  • Space complexity: O (1)
Published 43 original articles · won praise 20 · views 1455

Guess you like

Origin blog.csdn.net/Chen_2018k/article/details/104547877