日期:2014-05-20  浏览次数:20750 次

用正则表达式如何表示合法的括号序列?
比如串:(())()(())
(()(())())
((()))
(())()(())()
也就是用正则表达式表示所有合法的括号串?

------解决方案--------------------
用常规的吧,感觉用正则有点难。
String s="(())()(())()";
Java code

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;
}

------解决方案--------------------
Java code

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;
    }
}

------解决方案--------------------

Java code

          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;