Q1:Valid Parentheses
Question:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
MyAnswer 1 (C++):
1 class Solution { 2 public: 3 bool isValid(string s) { 4 char stack[s.size()]; 5 int i = 0; 6 int j = 0; 7 8 //cout << s; 9 10 if(s[j] == ')' || s[j] == ']' || s[j] =='}') 11 return false; 12 else if(s[j] == '\0') 13 return true; 14 else 15 stack[i++] = s[j++]; 16 17 while(1) 18 { 19 switch(s[j]) 20 { 21 case '\0': 22 if(i == 0) 23 return true; 24 else 25 return false; 26 case ')': 27 if(stack[i-1] != '(') 28 return false; 29 else 30 { 31 i -= 1; 32 j += 1; 33 } 34 break; 35 case ']': 36 if(stack[i-1] != '[') 37 return false; 38 else 39 { 40 i -= 1; 41 j += 1; 42 } 43 break; 44 case '}': 45 if(stack[i-1] != '{') 46 return false; 47 else 48 { 49 i -= 1; 50 j += 1; 51 } 52 break; 53 default: 54 stack[i++] = s[j++]; 55 break; 56 } 57 } 58 } 59 };
数组模拟栈,匹配到括号则出栈,否则入栈
MyAnswer 2 (Java):
1 public class Solution { 2 public boolean isValid(String s) { 3 ArrayList<Character> stack = new ArrayList<Character>(); 4 int i = 0; 5 for(i = 0; i < s.length(); i++){ 6 switch(s.charAt(i)){ 7 case ')': 8 if(stack.isEmpty() || stack.get(stack.size()-1) != '(') 9 return false; 10 else 11 stack.remove(stack.size()-1); 12 break; 13 case ']': 14 if(stack.isEmpty() || stack.get(stack.size()-1) != '[') 15 return false; 16 else 17 stack.remove(stack.size()-1); 18 break; 19 case '}': 20 if(stack.isEmpty() || stack.get(stack.size()-1) != '{') 21 return false; 22 else 23 stack.remove(stack.size()-1); 24 break; 25 default: 26 stack.add(s.charAt(i)); 27 break; 28 } 29 } 30 if(stack.isEmpty()) 31 return true; 32 else 33 return false; 34 } 35 }

浙公网安备 33010602011771号