Subject description:
Includes only a given '(', ')' string, '{', '}', '[', ']', and determine whether the string is valid.
Valid string must meet:
Left bracket must be closed by a closing parenthesis of the same type.
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: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
Topic Analysis:
LinkedList use as an auxiliary stack:
- Traversing the input string
- If the current character to the left half of the brackets, it is pushed onto the stack
- If you come across the right half of the brackets, Category talk:
- 1) If the stack is not empty and the left half of the corresponding bracket, the top element is removed, continue to cycle
- 2) If the stack is empty at this time, the process directly returns false
- 3) If the left half of the corresponding bracket, false otherwise
Code:
package com.company; import java.util.LinkedList; public class Main { public static void main(String[] args) { String str = "]"; System.out.println(isValid(str)); } private static boolean isValid(String s) { if (s == null || s.isEmpty()) { return true; } LinkedList<Character> linkedList = new LinkedList<>(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch == '(' || ch == '[' || ch == '{') { linkedList.add(ch); // no element in the stack, and the current symbol is a right parenthesis, directly returns false, the current symbol does not need to push The else {} if (linkedList.isEmpty()) { return false; } if (ch == ')') { if (linkedList.peekLast() != '(') { return false; } } if (ch == ']') { if (linkedList.peekLast() != '[') { return false; } } if (ch == '}') { if (linkedList.peekLast() != '{'){ return false; } } if (!linkedList.isEmpty()) { linkedList.removeLast(); } } } return linkedList.isEmpty(); } }
Time complexity: O (N), traversed again, n is the size of length of str
Space complexity: O (N), LinkedList size n, i.e. the auxiliary stack size