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;
}
}
Reference: [. 1].
Http://www.iteye.com/topic/1055854
Reproduced in: https: //my.oschina.net/itfanr/blog/195704