用Java写一个函数判断字符串中"{"与"}"匹配? 提示:"{"与"}"必须同时出现,"{"必须在"}"前面,允许嵌套
[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.regex.Matcher;
import java.util.regex.Pattern;
public class TestCurlyBraces
{
private Pattern pattern = Pattern.compile("[^{}]*(\\{[^{}]*(\\{[^{}]*\\}[^{}]*)*\\}[^{}]*)*[^{}]*");
/**
* @param args
*/
public static void main(String[] args)
{
TestCurlyBraces instance = new TestCurlyBraces();
String input = "asda{asd{fsfsff}sdfab245}2{32}";
instance.match(input);
}
public void match(String input)
{
Matcher match = pattern.matcher(input);
if (match.matches())
System.out.println(match.group());
else
System.out.println("not matched.");
}
}