给定一个字符串A和它的长度n,判断是否为一个合法的括号串。
判断括号串是否合法即括号是否匹配,是否成对出现
import java.util.*;
public class test3 {
public static boolean chkParenthesis(String A, int n) {
char[] arrC = A.toCharArray();
int num = 0;
int i = 0;
while(i < arrC.length && num >= 0){
if(arrC[i] == '('){
num++;
}else if(arrC[i] == ')'){
num--;
}
i++;
}
if(i < arrC.length || num != 0){
return false;
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str1 = scanner.nextLine();
Integer n = scanner.nextInt();
System.out.println(chkParenthesis(str1,n));
}
}
运算结果:
( ( ( ( ) ) ) )
8
true
本文介绍了一种用于判断括号串是否合法的算法,通过遍历字符串并使用计数器来跟踪括号的开闭状态,确保每个左括号都有对应的右括号。此算法在字符串处理和语法分析中具有广泛应用。
1143

被折叠的 条评论
为什么被折叠?



