日期:2014-05-20 浏览次数:20822 次
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; } }
------解决方案--------------------
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;