论坛首页 综合技术论坛

括号匹配

浏览 2221 次
锁定老帖子 主题:括号匹配
精华帖 (0) :: 良好帖 (0) :: 新手帖 (6) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-05-20   最后修改:2010-05-20
/**
 * 括号匹配
 * 
 * @author fangtengfei
 * @date 2010-5-15
 */
public class ParenthesesMatching {

 public static void main(String[] args) {
  // String c="((((()()))()()())";
  String c = "((((()))))()";
  // String c="(((()()))()()())";
  // String c="()()(())";
  boolean hasMatch = ParenthesesHasMatching(c.toCharArray());
  System.out.println(hasMatch);
 }

 private static boolean ParenthesesHasMatching(char[] charArray) {
  // 括号匹配值,等于0则代表匹配,小于0直接退出,遇到(加1 遇到)-1
  int matchValue = 0;
  for (char c : charArray) {
   if (c == '(') {
    matchValue += 1;
   }
   if (c == ')') {
    matchValue -= 1;
   }
   if (matchValue < 0) {
    return false;
   }
  }
  return matchValue == 0;
 }

}

 

   发表时间:2010-05-24  
我觉得这个做法是有问题的。如果输入的第一个就是‘)()(’,这个程序也会输出正确
0 请登录后投票
   发表时间:2010-05-25  
weijizg 写道
我觉得这个做法是有问题的。如果输入的第一个就是‘)()(’,这个程序也会输出正确

‘)()(’这个我验证了一下,返回false。。
0 请登录后投票
论坛首页 综合技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics