括号配对问题
时间限制:3000 ms | 内存限制:65535 KB
难度:3
- 描述
-
现在,有一行括号序列,请你检查这行括号是否配对。
- 输入
- 第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符
- 输出
- 每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
- 样例输入
-
3
[(])
(])
([[]()]) - 样例输出
-
No
No
Yes
思路:依次将括号放入栈类型数组中,当遇到m和m-1正好匹配时,从栈中删去m和m-1从而得知是否匹配
代码:
import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class BracketsMatch {
public static void main(String[] args){
int aa = 0,bb=0;
Scanner in = new Scanner (new BufferedInputStream(System.in));
int a = in.nextInt();
while(a--!=0){
String n = in.next();
List<Character> list = new ArrayList();
list.add(' ');
for(int i = 1;i<n.length();i++ ){
char t = n.charAt(i);
list.add(t);
int m = list.lastIndexOf(n.charAt(i));
int gg = (int)list.get(m);
int tt = (int)list.get(m-1);
if(tt==gg-1 ||tt == gg-2){
list.remove(m);
list.remove(m-1);
}
}
if(list.size()==2){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
}
}
import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class BracketsMatch {
public static void main(String[] args){
int aa = 0,bb=0;
Scanner in = new Scanner (new BufferedInputStream(System.in));
int a = in.nextInt();
while(a--!=0){
String n = in.next();
List<Character> list = new ArrayList();
list.add(' ');
for(int i = 1;i<n.length();i++ ){
char t = n.charAt(i);
list.add(t);
int m = list.lastIndexOf(n.charAt(i));
int gg = (int)list.get(m);
int tt = (int)list.get(m-1);
if(tt==gg-1 ||tt == gg-2){
list.remove(m);
list.remove(m-1);
}
}
if(list.size()==2){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
}
}