您的位置:首页 > 编程语言 > Java开发

java括号匹配

2014-12-20 00:00 295 查看
package com.duapp.itfanr;

public class CharDemo{
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") );
}
}

package com.duapp.itfanr;

import java.util.LinkedList;

public class CharDemo
{
private LinkedList<Character> stack = new LinkedList<Character>();

/**
* @param args
*/
public static void main(String[] args)
{
CharDemo matcher = new CharDemo();
System.out.println(matcher.matches("{{{{}}a}ab}}"));
}

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;
}
}
参考: [1].
http://www.iteye.com/topic/1055854
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java