1. 程式人生 > >演算法題013 -- [Valid Parentheses] by java

演算法題013 -- [Valid Parentheses] by java

題目

判斷字串中的括號是否有效。要求括號成對出現,並且括號順序對應上。例如:[12(fgsf)4]-有效、{d[]df34}-有效、{f3[aer)}-無效、{3)32}-無效。

分析

依然考察的是程式碼能力,還有對棧的整體概念;有意思的是,這條題目的編碼,相對而言其實會比之前一些中等難度的演算法,還要難寫,邊界條件考慮的要很多;

思路

邊界條件的考慮:考慮到存在這些括號字元的同時,也要考慮到不包含這些括號的字串;
使用java中stack類;

程式碼

package algorithm013;

import java.util.Stack;

public
class Algorithm013 { public static void main(String[] args) { String s = "asdf";// false String s2 = "()[]{}";// true String s3 = "{(1)2}3[]4";// true String s4 = "[}{()]";// false String s5 = "[12(fgsf)4]";// true String s6 = "{d[]df34}";// true String s7 = "{f3[aer)}";// false String s8 = "{3)32}"
;// false System.out.println(isValidParentheses(s)); System.out.println(isValidParentheses(s2)); System.out.println(isValidParentheses(s3)); System.out.println(isValidParentheses(s4)); System.out.println(isValidParentheses(s5)); System.out.println(isValidParentheses(s6)); System.out.println
(isValidParentheses(s7)); System.out.println(isValidParentheses(s8)); } @SuppressWarnings("unchecked") public static boolean isValidParentheses(String test) { if (null != test && !"".equals(test)) { @SuppressWarnings("rawtypes") Stack stack = new Stack(); boolean isValid = false; int length = test.length(); for (int i = 0; i < length; i++) { char c = test.charAt(i); if('(' == c || '{' == c || '[' == c ) { isValid = true; stack.push(c); continue; } if(')' == c || '}' == c || ']' == c) { isValid = true; if(stack.isEmpty()) return false; char pop = (char) stack.pop(); if(!(('(' == pop && ')' == c) || ('{' == pop && '}' == c) || ('[' == pop && ']' == c))) { return false; } } } return isValid && stack.isEmpty(); } return false; } }