java 符号匹配的四种方法


import java.util.HashMap;
import java.util.Stack;

public class match {
	public boolean match1(String s) {

		if (s.contains("()") || s.contains("[]") || s.contains("{}")) {
			s = s.replace("()", "");
			s = s.replace("[]", "");
			s = s.replace("{}", "");
			return s.length() == 0;
		} else {
			return false;
		}
	}

	public boolean match5(String s) {
		StackCharacter stack = new StackCharacter();
		char[] arr = s.toCharArray();
		for (char c : arr) {
			if (c == '(') {
				stack.push(')');
			} else if (c == '[') {
				stack.push(']');
			} else if (c == '{') {
				stack.push('}');
			} else {
				if (stack.isEmpty() || stack.pop() != c) {
					return false;
				}

			}
		}
		return stack.isEmpty();

	}
	public boolean match5(String s) {
		StackCharacter stack = new StackCharacter();
		HashMapCharacter, Character map = new HashMapCharacter, Character();
		map.put('(', ')');
		map.put('[', ']');
		map.put('{', '}');
		
		for(int i=0;is.length();i++){
			char ch = s.charAt(i);
			if(map.containsKey(ch)) {
				stack.push(ch);
			}
			else {
				if(stack.isEmpty() ) {
					return false;
				}
				else {
					char ele = stack.pop();
					if(ch!=map.get(ele) ) {
						return false;
					}
				}
			}
		}
		return stack.isEmpty();
	}
public boolean match5(String s) {
	StackCharacter stack = new StackCharacter();
	for(int i=0;is.length();i++){
		char ch = s.charAt(i);
		if(ch=='('||ch=='['||ch=='{') {
			stack.push(ch);
		}
		else {
			if(stack.isEmpty() ) {
				return false;
			}
			else {
				char ele = stack.pop();
				if(ele=='('ch!=')' || ele=='['ch!=']' || ele=='{'ch!='}') {
					return false;
				}
			}
		}
	}
	return stack.isEmpty();
}
	public static void main(String[] args) {
		match test = new match();
		String s = "{[()]}";
		System.out.println(test.match1(s));
		System.out.println(test.match5(s));
		System.out.println(test.match5(s));
		System.out.println(test.match5(s));
	}

}
提示:
1,match5是match5的升级版,看起来更高大上一点有么有😄
2,char 类型时用' '单引号
3,match1--暴力破解法    match5--字符串转化为char数组+for each 方法
+stack push相反符号的方法
match5 -- hashmap存储左右符号为key,value,使用map.containsKey()方法
进行stack  push+map.get()方法做相反符号的判断。
match5 --match5的降级版
最新回复(0)
/jishuuxjGKkd89Q1oKo0ZICKS1IPU6GnGcoEeZO_2FI717Fswk_3D4858621
8 简首页