题目描述:
给定一个字符串所表示的括号序列,包含以下字符: ‘(‘, ‘)‘
, ‘{‘
, ‘}‘
, ‘[‘
and ‘]‘
, 判定是否是有效的括号序列。括号必须依照 "()"
顺序表示, "()[]{}"
是有效的括号,但 "([)]"
则是无效的括号。
解答:
1 import java.util.LinkedList; 2 3 /** 4 * Created by Tutotu on 2017/2/11. 5 * <p> 6 * Realname:yangmingzhu 7 * <p> 8 * Tel:18511400217 9 * <p> 10 * Email:yangmingzhu921025@hotmail.com 11 */ 12 13 public class Solution8 { 14 15 LinkedList<Character> stack = new LinkedList<Character>(); 16 17 public boolean isValidParentheses(String s) { 18 // Write your code here 19 boolean result = false; 20 if(s.length() == 0){ 21 return false; 22 }else { 23 char[] c = s.toCharArray(); 24 for(int i=0; i<s.length(); i++){ 25 26 if(stack.isEmpty()){ 27 push(stack,c[i]); 28 }else{ 29 if(stack.getLast() == reverse(c[i])){ 30 char tmp = pop(stack); 31 if(tmp == ‘)‘ || tmp == ‘}‘ || tmp == ‘]‘){ 32 result = false; 33 break; 34 } 35 }else{ 36 push(stack,c[i]); 37 } 38 } 39 System.out.println(stack); 40 } 41 if(isEmpty(stack)) result = true; 42 } 43 44 return result; 45 } 46 47 private char pop(LinkedList<Character> stack){ 48 return stack.removeLast(); 49 } 50 51 private void push(LinkedList<Character> stack, char s){ 52 stack.addLast(s); 53 } 54 55 private boolean isEmpty(LinkedList<Character> stack){ 56 if (stack.isEmpty()){ 57 return true; 58 }else 59 return false; 60 61 } 62 63 private char reverse(char c){ 64 char res = ‘ ‘; 65 if (c == ‘(‘) res = ‘)‘; 66 else if(c == ‘)‘) res = ‘(‘; 67 else if(c == ‘[‘) res = ‘]‘; 68 else if(c == ‘]‘) res = ‘[‘; 69 else if(c == ‘{‘) res = ‘}‘; 70 else if(c == ‘}‘) res = ‘{‘; 71 return res; 72 } 73 74 public static void main(String[] args){ 75 Solution8 s = new Solution8(); 76 System.out.println(s.isValidParentheses("([])")); 77 } 78 }
解题思路:拿题之后,想了一下,想到了数据结构中的表达式判断一节中就涉及了括号匹配,马上确定了应该用栈来做。
原文:http://www.cnblogs.com/tutotu/p/6389250.html