package javaTest; import java.util.Stack; public class JavaTest { public static boolean solve(StringBuilder str) { if (str.length() == 0) return false; Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); switch (ch) { case '{': case '[': case '(': if (!stack.empty()) { char chX = stack.peek(); if ((ch == '{' && chX == '{') || (ch == '{' && chX == '[') || (ch == '{' && chX == '(') || (ch == '[' && chX == '[') || (ch == '[' && chX == '(') || (ch == '(' && chX == '(')) { return false; //左括号入栈前,要判断优先级,如果不符合,则false } else { stack.push(ch); //符合优先级,则入栈 } } else { stack.push(ch); } break; case '}': case ']': case ')': if (!stack.empty()) { char chX = stack.pop(); if ((ch == '}' && chX != '{') || (ch == ']' && chX != '[') || (ch == ')' && chX != '(')) return false; } else { return false; } break; default: break; } } if (!stack.empty()) //栈内不为空,则证明还有左括号没有匹配,所以false return false; else return true; } public static void main(String[] args) { StringBuilder str = new StringBuilder(); str.append("(){}[]{[]}([])"); System.out.print(solve(str)); } }
static boolean isMatch(String s) { Stack<Character> sk = new Stack<Character>(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { sk.push('('); } if (s.charAt(i) == ')') { if (!sk.isEmpty() && sk.pop() == '(') continue; else return false; } if (s.charAt(i) == '[') { sk.push('['); } if (s.charAt(i) == ']') { if (!sk.isEmpty() && sk.pop() == '[') continue; else return false; } } if (sk.isEmpty()) return true; else return false; }
#include<iostream> #include<string> #include<stack> using namespace std; bool IsMatch(string str) { int i=0; stack<char> stk; bool flag=true; while(str[i]!='\0'&&flag==true) { switch(str[i]) { case '(': case '[': case '{':stk.push(str[i]);break; case ']': { if(stk.top()=='[') stk.pop(); else flag = false; break; } case ')': { if(stk.top()=='(') stk.pop(); else flag = false; break; } case '}': { if(stk.top()=='{') stk.pop(); else flag = false; break; } } i++; } if(!stk.empty()) flag=false; return flag; } void main() { string str; char c; while((c=cin.get())!='\n') str=str+c; if(IsMatch(str)) cout<<"正确"<<endl; else cout<<"不正确"<<endl; }
import java.util.Stack;
public class Solution{
public boolean isMatch(String str){
Stack stack = new Stack();
for(int i = 0; i < str.length(); ++i){
char ch = str.charAt(i);
if(ch == '[' || ch == '{' || ch == '('){
stack.push(ch);
} else if(ch == ']' || ch == '}' || ch == ')'){
if(stack.isEmpty()){
return false;
}
char top = stack.peek();
if(ch == ']' && top == '[' || ch == '}' && top == '{' || ch == ')' && top == '('){
stack.pop();
}
else{
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args){
String str = "{{[sda]}}}()";
Solution solution = new Solution();
System.out.println(solution.isMatch(str));
}
}
public static boolean Judge(String str){ if(str==null||str.trim().equals("")){ return false; } HashMap<Character , Character> Brackets=new HashMap<Character, Character>(); Brackets.put('(', ')'); Brackets.put('{', '}'); Brackets.put('[', ']'); char ch[] =str.toCharArray(); int length = ch.length; if(length%2!=0){ return false; } for(int i = 0 ; i<length/2 ;i++ ){ try{ if(Brackets.get(ch[i])!=ch[length-i-1]){ return false; } }catch(Exception e){ return false; } } return true; }
使用栈就可以简单解决:遍历字符串,遇到左括号就入栈,遇到右括号就和栈定比较是否匹配,若匹配则栈定出栈,继续遍历。 import java.util.Scanner; import java.util.Stack; /** * @Title: * @Description: * @author: zwq * @date: 2020/2/813:57 */ public class Kuohao { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = ""; if (in.hasNext()){ str = str + in.next(); } if(kuoHaoStack(str)){ System.out.println(true); }else { System.out.println(false); } } public static boolean kuoHaoStack(String str){ Stack<String> stringStack = new Stack<>(); for (int i=0;i<str.length();i++){ String current = strAt(str,i); int leftOrRight = leftOrRight(current); if(leftOrRight == -1){ stringStack.push(current); }else if(leftOrRight == 1){ String top = stringStack.peek(); if(kuoHaoPiPei(top,current)){ stringStack.pop(); }else { return false; } } } return true; } /** * 判断括号匹配 * @return */ public static boolean kuoHaoPiPei(String a,String b) { if (a.equals("(") || b.equals(")")) return true; if (a.equals("[") || b.equals("]")) return true; if (a.equals("{") || b.equals("}")) return true; if (b.equals("(") || a.equals(")")) return true; if (b.equals("[") || a.equals("]")) return true; if (b.equals("{") || a.equals("}")) return true; return false; } /** * 判断括号为左括号或者右括号 * @param str * @return: 1:右括号,-1:左括号,0:其他 */ private static int leftOrRight(String str){ if(str.equals(")") || str.equals("]") || str.equals("}")){ return 1; }else if(str.equals("(") || str.equals("[") || str.equals("{")){ return -1; } return 0; } /** * 获取某个位置字符 * @param str * @param i * @return */ private static String strAt(String str,int i){ String currentStr = str.substring(i,i+1); return currentStr; } }
/**
* 括号匹配问题
* 要求:满足正确的匹配关系(包括括号正确配对与{[(的正确嵌套)
* 解决:利用栈的思想依次将符号入站(紧急匹配的符号一定在栈顶)
* 如果刚好匹配则出栈(在这里需要注意在入栈时进行嵌套关系判断 即栈中只有左边括号)
*/
public class 括号匹配 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
char[] arr = str.toCharArray();
Boolean flag = check(arr);
System.out.println(flag);
}
private static Boolean check(char[] arr) {
Stack<Character> stack = new Stack<Character>();
// System.out.println(stack.peek());
for (int i = 0; i < arr.length; i++) {
if (stack.isEmpty()) {
stack.push(arr[i]);
} else {
if (compareNest(stack.peek(), arr[i])) {
if (compareSuit(stack.peek(), arr[i])) {
// 正确匹配,出栈
stack.pop();
} else {
stack.push(arr[i]);
}
}
// 嵌套关系错误
else {
return false;
}
}
}
if (stack.isEmpty())
return true;
else
return false;
}
// 确定c1,c2 能否嵌套“{[(”
public static Boolean compareNest(char c1, char c2) {
if (c1 == '(') {
if (c2 == '(' || c2 == ')') {
return true;
} else {
return false;
}
} else if (c1 == '[') {
if (c2 == '[' || c2 == '(' || c2 == ']') {
return true;
} else {
return false;
}
} else
return true;
}
// 比较是否匹配
public static Boolean compareSuit(char c1, char c2) {
if (c1 == '(' && c2 == ')' || c1 == '[' && c2 == ']' || c1 == '{' && c2 == '}')
return true;
else
return false;
}
}
public boolean init(String s){
for(int i=0;i<s.length();i++){
switch(s.charAt(i)){
case '{': if(s.charAt(s.length()-1-i)!='}'){return false;}break;
case '[': if(s.charAt(s.length()-1-i)!=']'){return false;}break;
case '(': if(s.charAt(s.length()-1-i)!=')'){return false;}break;
}
}
return true;
}
#include <iostream> #include <stack> using namespace std; bool str_match(const char * p) { stack<char> st; while(*p!='\0') { if(*p=='(' || *p=='{' || *p=='[') { st.push(*p); } if(*p==')' || *p=='}' || *p==']') { if(st.empty()) return false; else { char q; q=st.top(); if(*p==')' ) { if(q=='(') { ++p; st.pop(); // continue; }else return false; }else if(*p=='}') { if(q=='{') { ++p; st.pop(); // continue; }else return false; }else { if(q=='[') { ++p; st.pop(); // continue; }else return false; } } } else ++p; } if(st.empty()) return true; else return false; } int main() { char * str="([*0780{lj;}k'{l])"; if(str_match(str)) cout<<"match sucess"<<endl; else cout<<"match faile"<<endl; return 0; }