括号匹配问题
1。判断括号是否成对出现
1 import java.util.Stack; 2 3 public class KuoHao 4 { 5 6 public boolean check(String str) 7 { 8 Stack<Character> stack = new Stack<Character>(); 9 boolean flag = true; 10 for (int i = 0; i < str.length() && flag; i++) 11 { 12 try 13 { 14 switch (str.charAt(i)) 15 { 16 case '(': 17 case '[': 18 case '{': 19 stack.push(str.charAt(i)); 20 break; 21 case ')': 22 if (stack.pop() != '(') 23 flag = false; 24 break; 25 case ']': 26 if (stack.pop() != '[') 27 flag = false; 28 break; 29 case '}': 30 if (stack.pop() != '{') 31 flag = false; 32 break; 33 } 34 } 35 catch (Exception e) 36 { 37 flag = false; 38 } 39 } 40 if (flag && !stack.isEmpty()) 41 flag = false; 42 43 return flag; 44 } 45 46 public static void main(String[] args) 47 { 48 KuoHao pm = new KuoHao(); 49 System.out.println("(: " + pm.check("(")); 50 System.out.println("a(bc[d])e{fd}: " + pm.check("a(bc[d])e{fd}")); 51 System.out.println("a(bc]d: " + pm.check("a(bc]d")); 52 System.out.println("a(b(c))d: " + pm.check("a(b(c))d")); 53 System.out.println("a(b)c)d: " + pm.check("a(b)c)d")); 54 } 55 }
2.问题描述:括号成对出现,查找第N个左括号与之匹配的右括号中的内容
例如:字符串:A((B)((CD)(E)F)) 查找第1左括号,输出(B)((CD)(E)F)
import java.util.Scanner;
public class KuoHao2 {
public static void search(int N,String s){
int i = 0,k=-1, w= -1;
do{
k = s.indexOf("(",k+1);
i++;
}while(i < N && k != -1);
if(k > 0){
int first = k+1;
System.out.println("查找字符串\""+s+"\"的第"+N+"个左括号内的内容,匹配起始位于字符串的第:"+(first)+"位");
w = s.indexOf(")",k+1);
w = a(w, k, s);
int end = w;
System.out.println("匹配结束位于字符串的第:"+(end+1)+"位");
System.out.println("输出为:"+s.substring(first,end ));
} else {
System.out.println("不存在')'");
}
}
public static int a(int w, int k, String s){
if(w > 0){
int m =1, n = 1;
boolean f = false;
do{
if(s.indexOf("(",k+1)>0 && s.indexOf("(",k+1) < w){
k = s.indexOf("(",k+1);
m += 1;
}
while( m > n ){
while(s.indexOf("(",k+1)>0 && s.indexOf("(",k+1) < w){
m++;
k = s.indexOf("(",k+1);
}
for(int j=0; j<=m-n; j++){
n++;
w = s.indexOf(")",w+1);
}
}
if(s.indexOf("(",k+1)>0 && s.indexOf("(",k+1) < w)
f = true;
else f = false;
}while(f);
} else {
System.out.println("不存在'('");
}
return w;
}
public static void main(String[] args) {
String s = "A((B)((CD)(E)F))";
Scanner ss = new Scanner(System.in);
int N = ss.nextInt();
search(N,s);
}
}
运行截图:


浙公网安备 33010602011771号