java-- 匹配{[()]}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test{
//匹配()[]{}
public static boolean check(String expr){
if(expr==null || "".equals(expr)) return true;
Listlist=new ArrayList ();
Mapmap=new HashMap ();
map.put("(", ")");
map.put("[", "]");
map.put("{", "}");
for(int i=0;iString ch=expr.charAt(i)+"";
if(map.keySet().contains(ch)){
list.add(ch);
}else if(map.values().contains(ch)){
if(list.isEmpty() || !ch.equals(map.get(list.get(list.size()-1)))){
return false;
}else{
list.remove(list.size()-1);
}
}
}
return list.isEmpty();
}
public static void main(String[] args) {
System.out.println(check("{([])}"));
System.out.println(check("{a(b[c{e}f(s)])}"));
System.out.println(check("{([]]]])}"));
}
}
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
System.out.println(isMatchs("(((()()())))"));
System.out.println(isMatchs("))))))))(1+1+1+1+1)((1+(1+1)))"));
}
/**
* 只包含括号,判断括号是否匹配
* @param express 你的表达式
* @return
*/
public static boolean isMatchs(String express){
//如果表达式是空的,匹配
if(express == null||express.trim().equals("")){
return true;
}
LinkedList
char[] ch = express.toCharArray();
for(int i = 0;i< ch.length;i++){
if(ch[i] == '('){
linkedList.addLast(ch[i]);
}else if(ch[i] == ')'){
while(linkedList.size()>0&&(linkedList.peekLast() != '(')&&(linkedList.peekLast() != ')')){
linkedList.removeLast();
}
if(linkedList.size()>0&&linkedList.peekLast() == '('){
linkedList.removeLast();
}else{
linkedList.addLast(ch[i]);
}
}else{
linkedList.addLast(ch[i]);
}
}
System.out.print("去完括号linkedList:");
out(linkedList);
//到最后没有括号剩余了
if((!linkedList.contains('(')&&!linkedList.contains(')'))){
return true;
}else{
return false;
}
}
/**
* 输出
* @param linkedList
*/
public static void out(LinkedList
for(Character character:linkedList){
System.out.print(character +"");
}
System.out.println();
}
}
如果匹配返回true 不匹配返回false 表达式可自行改写。
public class test1 {
public static void main(String[] args) throws Exception {
String a = "(2+3)*3";
String b = "()";
int n = 0;
int m = 0;
char item1 = 0;
char item2 = b.charAt(0);
for (int i = 0; i < a.length(); i++) {
item1 = a.charAt(i);
n = n + 1;
}
item2 = b.charAt(1);
for (int i = 0; i < a.length(); i++) {
item2 = a.charAt(i);
m = m + 1;
}
if( n == m){
System.out.println(true);
}else{
System.out.println(false);
}
}
}