用正则表达式如何表示合法的括号序列? 比如串:(())()(())(()(())())((()))(())()(())()也就是用正则表达式表示所有合法的括号串? 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 用常规的吧,感觉用正则有点难。String s="(())()(())()";public boolean checkValid(String s){int count=0;int index=0;while(count>=0){if(s.charAt(index)=='('){count++;}else if(s.charAt(index)==')'){}index++;if(index==s.length()-1){break;}}if(count!=0){System.out.println("不合法的");return false;}return true;} public class Test { public static void main(String[] args) { String s="(())()(())()"; checkValid(s); } public static boolean checkValid(String s) { int count = 0; int index = 0; while (count >= 0){ if (s.charAt(index) == '(') { count++; } else if (s.charAt(index) == ')') { count--; } index++; if (index==(s.length())) { break; } } if (count != 0) { System.out.println("不合法的"); return false; } System.out.println("合法的"); return true; }} 如LS的,转换成char数组后循环处理。判断(与)个数是否相等 可以配合正则:if(str.replaceAll("[^\(]","").length==str.replaceAll("[^\)]","").length) System.out.println("合法");else System.out.println("不合法"); String input = "(())()(())"; String input2; boolean validate = false; while(true) { input2 = input.replaceAll("([(][)])*", ""); if(input2.length() == input.length()) { break; } input = input2; } if(input.trim().equals("")) validate = true; 正则表达式有分组捕获匹配功能来验证匹配的括号,但现在java的正则表达式没有此功能,以后不知道会不会追加该功能 这样设计算法如(()())从左至右遍历字符串,定义计数器c=0当字符是左括号时,计数器c+1当字符时右括号时,计数器c-1一旦发现计数器的值小于0,说明括号不匹配思路就是这样,我试验过,可行. 求助 关于java读文件的问题,请教 关于继承中构造函数的调用!很奇怪,高人来指点!! Object类的输出问题. Java document的谬误? windows下安装eclipse的cdt插件,应该怎样运行它的项目呢? Map接口问题 关于ToolTip:我要在自己的视图上,当鼠标移到某个位置的时候,显示一个tooltip,怎么做? 什么叫属性文件? 想考scjp,看什麽书好呢 正则表达式匹配 想个24点的java问题
String s="(())()(())()";public boolean checkValid(String s){
int count=0;
int index=0;
while(count>=0){
if(s.charAt(index)=='('){
count++;
}
else if(s.charAt(index)==')'){
}
index++;
if(index==s.length()-1){
break;
}
}
if(count!=0){
System.out.println("不合法的");
return false;
}
return true;
}
public class Test {
public static void main(String[] args) {
String s="(())()(())()";
checkValid(s); }
public static boolean checkValid(String s) {
int count = 0;
int index = 0;
while (count >= 0){
if (s.charAt(index) == '(') {
count++;
} else if (s.charAt(index) == ')') {
count--;
}
index++;
if (index==(s.length())) {
break;
}
}
if (count != 0) {
System.out.println("不合法的");
return false;
}
System.out.println("合法的");
return true;
}
}
System.out.println("合法");
else
System.out.println("不合法");
String input2;
boolean validate = false;
while(true)
{
input2 = input.replaceAll("([(][)])*", "");
if(input2.length() == input.length())
{
break;
}
input = input2;
}
if(input.trim().equals(""))
validate = true;
(()())
从左至右遍历字符串,定义计数器c=0
当字符是左括号时,计数器c+1
当字符时右括号时,计数器c-1
一旦发现计数器的值小于0,说明括号不匹配思路就是这样,我试验过,可行.