topic:
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.
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/valid-parentheses
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
Ideas:
The use of a stack data structure;
Java implementation:
1 import java.util.Stack; 2 3 class Solution { 4 public boolean isValid(String s) { 5 6 Stack<Character> stack = new Stack<>(); 7 for (int i = 0; i<s.length(); i++){ 8 char c = s.charAt(i); 9 if(c == '('||c == '['|| c == '{') 10 stack.push(c); 11 else{ 12 if(stack.isEmpty()) 13 return false; 14 char topChar = stack.pop(); 15 if(c==')'&& topChar != '(') 16 return false; 17 if(c==']'&& topChar != '[') 18 return false; 19 if(c=='}'&& topChar != '{') 20 return false; 21 } 22 } 23 return stack.isEmpty(); 24 } 25 }