括号匹配问题 问题描述:给定一个包括 ’ ( ‘,’ ) ‘,’ [ ‘,’ ] ‘,’ { ‘,’ } '的字符串,判断字符串是否有效; 字符串需要满足: (1)左括号必须用相同类型的右括号匹配; (2)左括号要以正确的方式闭合; 注意:空字符串被认为是有效字符串; 解题思路: (1)遍历当前字符串,依次取出每个字符;如果当前字符是左括号,就把当前字符入栈; (2)如果当前字符是右括号,那么就取出栈顶元素,看看栈顶元素和当前元素是否匹配. a)匹配:则将栈顶元素出栈,继续取下一个字符; b)不匹配:直接返回false; (3)遍历整个字符串之后,若栈为空,则返回true,反之返回false;
public static boolean matching ( String s) {
Stack< Character> stack = new Stack < > ( ) ;
Map< Character, Character> map = new HashMap < > ( ) ;
map. put ( '(' , ')' ) ;
map. put ( '[' , ']' ) ;
map. put ( '{' , '}' ) ;
for ( int i = 0 ; i < s. length ( ) ; i++ ) {
char c = s. charAt ( i) ;
if ( c == '(' || c == '[' || c == '{' ) {
stack. push ( c) ;
continue ;
}
if ( stack. empty ( ) ) {
return false ;
}
Character top = stack. pop ( ) ;
if ( map. get ( top) == c) {
continue ;
}
}
if ( stack. empty ( ) ) {
return true ;
}
return false ;
}
用队列实现栈的功能 : 问题描述:使用队列实现栈的如下操作: (1) push操作:入栈 (2) pop操作:去除栈顶元素 (3) top操作:取栈顶元素 (4) empty操作:
public class MyStackByTwoQueue {
private static Queue< Integer> A = new LinkedList < > ( ) ;
private static Queue< Integer> B= new LinkedList < > ( ) ;
public static void push ( int x) {
A. offer ( x) ;
}
public static Integer pop ( ) {
if ( empty ( ) ) {
return null;
}
while ( A. size ( ) > 1 ) {
int tmp = A. poll ( ) ;
B. offer ( tmp) ;
}
int ret = A. poll ( ) ;
swapAB ( ) ;
return ret;
}
private static void swapAB ( ) {
Queue< Integer> tmp = new LinkedList < > ( ) ;
tmp = A;
A = B;
B = tmp;
}
public static Integer top ( ) {
if ( empty ( ) ) {
return null;
}
while ( A. size ( ) > 1 ) {
int tmp = A. poll ( ) ;
B. offer ( tmp) ;
}
int ret = A. poll ( ) ;
B. offer ( ret) ;
swapAB ( ) ;
return ret;
}
public static boolean empty ( ) {
return ( A. isEmpty ( ) && B. isEmpty ( ) ) ;
}
}
public class MyQueueByTwoStack {
private static Stack< Integer> A = new Stack < > ( ) ;
private static Stack< Integer> B = new Stack < > ( ) ;
public static void push ( int x) {
while ( ! B. empty ( ) ) {
int tmp = B. pop ( ) ;
A. push ( tmp) ;
}
A. push ( x) ;
}
public static Integer pop ( ) {
if ( empty ( ) ) {
return null;
}
while ( ! A. isEmpty ( ) ) {
int tmp = A. pop ( ) ;
B. push ( tmp) ;
}
return B. pop ( ) ;
}
public static Integer peek ( ) {
if ( empty ( ) ) {
return null;
}
while ( ! A. isEmpty ( ) ) {
int tmp = A. pop ( ) ;
B. push ( tmp) ;
}
return B. peek ( ) ;
}
public static boolean empty ( ) {
return ( A. isEmpty ( ) && B. isEmpty ( ) ) ;
}
}