网络整理 用java写一个函数判断字符串中"{"与"}"匹配?提示:"{"与"}"必须同时出现,"{"必须在"}"前面,允许嵌套 解法一: public class T { public static boolean isMatch(String value) { int numCount = 0, numMatch = 0; for (int i=0; null != value && i<value.length(); i++) { char ch = value.charAt(i); if (ch == '{') { numCount ++; numMatch ++; } else if (ch == '}') { numCount --; } if (numCount < 0) { return false; } } return (numMatch > 0 && numCount == 0); } public static void main(String args[]) { System.out.println( "=========must false=====" ); System.out.println( isMatch(null) ); System.out.println( isMatch("") ); System.out.println( isMatch("ddddd") ); System.out.println( isMatch("d{dddd") ); System.out.println( isMatch("dd{}}ddd") ); System.out.println( isMatch("d}dd{dd") ); System.out.println( "=========must true=====" ); System.out.println( isMatch("dd{}ddd") ); System.out.println( isMatch("ddd{{}d}d") ); System.out.println( isMatch("d{d{d}d}d") ); } } 解法二:考虑用栈 import java.util.LinkedList; public class CurlyBracesMatcher { private LinkedList<Character> stack = new LinkedList<Character>(); /** * @param args */ public static void main(String[] args) { CurlyBracesMatcher matcher = new CurlyBracesMatcher(); System.out.println(matcher.matches("{{{{}}a}a}")); } public boolean matches(String string) { if (string == null || string.length() == 0 || string.trim().equals("")) return true; int i = 0; while (i < string.length()) { char ch = string.charAt(i); if (ch == '{') { stack.push(ch); } else if (ch == '}') { if (stack.isEmpty()) return false; stack.pop(); } i++; } if (!stack.isEmpty()) return false; return true; } }