首页 > 试题广场 >

合法括号序列判断

[编程题]合法括号序列判断
  • 热度指数:14470 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

给定一个字符串A和其长度n,请返回一个bool值代表它是否为一个合法的括号串(只能由括号组成)。

测试样例:
"(()())",6
返回:true
测试样例:
"()a()()",7
返回:false
测试样例:
"()(()()",7
返回:false
import java.util.*;

public class Parenthesis {
    public boolean chkParenthesis(String A, int n) {
        // 使用栈的方法来解决
        if (n % 2 != 0) {
            return false;
        }
        Stack<Character> stack = new Stack();
        for (char a : A.toCharArray()) {
            if (a == '(') {
                stack.push(a);
            } else if (a == ')') {
                if (stack.isEmpty()) {
                    return false;
                } else if (stack.peek() == '(') {
                    stack.pop();
                } else {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}
发表于 2023-08-09 05:47:40 回复(1)
import java.util.*;

public class Parenthesis {
    public boolean chkParenthesis(String A, int n) {
        //n必须为偶数,这样才括号匹配
        if(n % 2 != 0){
            return false;
        }
        Stack<Character> stack = new Stack<>();
        for(int i = 0;i < A.length();i++){
            if(A.charAt(i) == '('){
                stack.push(A.charAt(i));
            }else{
                if(stack.empty()){
                       return false;
                    }else if(A.charAt(i) == ')'){
                        if( stack.peek() == '('){
                            stack.pop();
                         }
                   }else if(A.charAt(i)>= 'a' && A.charAt(i) <= 'z'){
                        return false;
                   }
                 }
        }
        if(!stack.empty()){
               return false;
        }
        return true;
    }
}

发表于 2022-03-29 14:52:26 回复(0)
import java.util.*;

public class Parenthesis {
    public boolean chkParenthesis(String A, int n) {
        //if(A.matches(/[0-9]*/)) return false;
        //if(A.matches(/['a'-'z']*/)) return false;
        //if(A.matches(/['A'-'Z']*/)) return false;
        if(n % 2 != 0) return false;
        int left = 0, right = 0;
        for(int i = 0; i < n; i++){
            if(A.charAt(i) == '(') left++;
            if(A.charAt(i) == ')') right++;
        }
        return (left + right) == n;
    }
}
发表于 2022-02-28 11:05:44 回复(0)
import java.util.*;

public class Parenthesis {
    public boolean chkParenthesis(String A, int n) {
        // write code here
        if (n % 2 != 0) return false;
        Stack<Character> stack = new Stack<>();
        char[] ch = A.toCharArray();
        for (int i = 0;i < ch.length;i++) {
            if (ch[i] == '(') {
                stack.push(ch[i]);
            } else if (ch[i] == ')') {
                if (!stack.isEmpty()) {
                    stack.pop();
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
        return stack.isEmpty();
    }
}

指针
import java.util.*;

public class Parenthesis {
    public boolean chkParenthesis(String A, int n) {
        // write code here
        int left = 0;
        for (int i = 0;i < A.length();i++) {
            if (A.charAt(i) == '(') {
                left++;
            } else if (A.charAt(i) == ')') {
                if (left > 0) {
                    left--;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
        return left == 0;
    }
}



发表于 2021-12-11 21:43:36 回复(0)
直接用字符串替换()就可以
 public boolean chkParenthesis(String A, int n) {
       if(n%2==1)
	  return false;
	while(n>0) {
	   A=A.replace("()", "");
	   if(A.length()<n) {
		n=A.length();
	   }else {
		break;
	   }
	}
	if(n==0)
	  return true;
	return false;
    }

发表于 2020-12-04 20:24:21 回复(0)
   public boolean chkParenthesis(String A, int n) {
        // write code here
        Deque<Character> stack = new ArrayDeque();
        Character ch = null;
        int i = 0;
        while(i<n){
            ch = A.charAt(i);
            if(ch == '('){
                stack.push(ch);
            }else if(stack.peek()!=null &&  ch == ')'){
                if(stack.peek() != '('){
                    return false;
                }else{
                    stack.pop();
                }

            }else if(stack.peek()==null){
                return false;
            }
            i++;
        }

        if(stack.isEmpty()){
            return true;
        }else{
            return false;
        }



    }
发表于 2020-07-16 22:16:50 回复(0)
import java.util.*;
/*
分别统计左右括号的数量,左括号++,右括号--,一旦出现负数 返回false
*/
public class Parenthesis {
    public boolean chkParenthesis(String A, int n) {
        // write code here
        int count = 0;
        for(int i= 0;i<n;i++){
            if(A.charAt(i)=='('){
                count++;
            }else if(A.charAt(i)==')'){
                if(count<=0)return false;
                count--;
            }
        }
        if(count==0)return true;
        return false;
    }
}

发表于 2020-06-16 19:34:52 回复(0)
import java.util.*;

public class Parenthesis {
    public boolean chkParenthesis(String A, int n) {
        // write code here
    	LinkedList<Character> st = new LinkedList<Character>();

    	for(int i = 0; i < n; i++) {
    		if (A.charAt(i) != '(' && A.charAt(i) != ')') {
    			return false;
    		}
    		
    		if(A.charAt(i) == '(') {
    			st.add('(');
    		}
    		
    		if(A.charAt(i) == ')') {
    			if(st.isEmpty()) {
    				return false;
    			}else {
    				st.removeLast();
    			}
    		}
    	}
    	
		if(st.isEmpty()) {
			return true;
		}else {
			return false;
		}
    }
}

发表于 2019-12-14 18:51:43 回复(0)
左括号入栈,遇见右括号时只需判断栈是否为空,不为则出栈,为空则右括号多了。否则就既不是左括号,也不是右括号
import java.util.*;
import java.lang.*;

public class Parenthesis {
    public boolean chkParenthesis(String A, int n) {
        Stack<Character> stack = new Stack<>();
        int stackLen = 0;
        for(int i = 0;i < n;i++) {
            char c = A.charAt(i);
        //左括号入栈
        if(c == '(') {
            stack.push(c);
            stackLen++;
        } else {    //右括号
            if(c == ')' && stackLen!=0){  //当前为右括号且栈里还有左括号
                stack.pop();
                stackLen--;
            } else {    //既不是左括号也不是右括号
                return false;
            }
        }
        }
        return true;
    }
}


编辑于 2019-08-18 15:27:10 回复(0)
import java.util.*;

public class Parenthesis {
    public boolean chkParenthesis(String A, int n) {
        // write code here
            //创建一个char数组用来保存左括号'('
        char[] stack = new char[n];
            // top用来记录存入的左括号的下标
        int top = 0;
            // 遍历字符串
        for(int i = 0;i< n;i++) {
                  // 当字符等于左括号时,并且数组下标top>0时
                  // 才能将左括号添加到字符数组中,如果少了top>0这个条件的话,
                  // 在当用例为)()(时,即先输入有括号时,会出现数组下标越界异常
            if(A.charAt(i)=='(' && top>=0) {
                stack[top++] = A.charAt(i);
            }else if(A.charAt(i)==')' && top>=0) {  
                         // 当字符为右括号时,消掉字符数组中对应的一个左括号
                         // 这里也要保证top>0,避免出现下标越界异常
                 top--;
            }else {
                return false;
            }
        }
            // 当top==0时,说明左括号和右括号一一对应,括号合法
        return top==0;
    }
}



发表于 2019-07-14 19:28:48 回复(1)

用一个栈来实现吧

Stack<Character> stack = new Stack<>();

    char[] chars = A.toCharArray();

    for (int i = 0; i < chars.length; i++) {
        if ('(' == chars[i]){
            stack.push('(');
        }else if (')' == chars[i]){
            if (stack.isEmpty()){
                return false;
            }
            stack.pop();
        }
    }

    if (stack.isEmpty()){
        return true;
    }else {
        return false;
    }
编辑于 2019-05-05 12:02:55 回复(0)
public static boolean isKuoHao(String ss,int n){
        if(n%2==0){
            ss=ss.replaceAll("\\(", "").replaceAll("\\)", "");
            if(ss.length()==0) return true;
            else return false;
        }else{
            return false;
        }
    }
发表于 2018-07-26 11:02:01 回复(0)
import java.util.*;

public class Parenthesis {
    public boolean chkParenthesis(String A, int n) {
        // write code here
        Stack<Character> stack = new Stack<>();
        char[] chars = A.toCharArray();
        for (int i = 0; i < n; i++) {
            if (chars[i] == '(') {
                stack.push(chars[i]);
            } else if (chars[i] == ')') {
                if (stack.size() > 0) {
                    if (stack.peek() == '(') {
                        stack.pop();
                    }
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
        return stack.size() == 0;
    }
}
使用栈,出栈入栈规则如下:
  1. 遇到左括号'(',压入栈;
  2. 遇到右括号')',需要根据栈的情况判断:若栈为空或栈顶元素不是左括号'(',则返回false;否则将栈顶元素弹出;
  3. 遇到其他符号直接返回
  4. 遍历至最后,若最终栈为空,返回true,否则返回false

发表于 2018-05-17 14:22:35 回复(0)
import java.util.*;

public class Parenthesis {
    public  boolean chkParenthesis(String A, int n) {
        boolean flag = false;
        
        if (null != A && !"".equals(A) && A.length() == n) {
            char[] arr = A.toCharArray();
            for (int i = 0; i < n; i++) {
                if (i == 0 && arr[i] != '(') {
                    flag = false;
                    break;
                } else if (i == (n - 1) && arr[i] != ')') {
                    flag = false;
                    break;
                } else if (arr[i] == '(' || arr[i] == ')') {
                    flag = true;
                } else {
                    flag = false;
                    break;
                }
            }
        }
        return flag;
    }
}

发表于 2018-03-21 10:33:43 回复(0)
import java.util.*;

public class Parenthesis {
    public boolean chkParenthesis(String A, int n) {
        // write code here
        Stack<String> stack=new Stack<>();
        for(int i=0;i<A.length();i++) {
            char c=A.charAt(i);
            switch (c) {
            case '(':
                stack.push("(");
                break;
            case ')':
                if(!stack.isEmpty()&&stack.pop().equals("("))
                    break;
                else {
                    return false;
                }
            default:
                return false;
            }
        }
        if(stack.isEmpty()) {
            return true;
        }else
            return false;
    }
}

发表于 2018-03-03 17:10:09 回复(0)
遇到左括号将其压如栈中;遇到右括号判断栈是否为空,如果为空,则括号不匹配,如果不为空出栈。
最后判断栈是否为空,空栈说明括号匹配,否则不匹配
import java.util.*;
public class Parenthesis {
    public boolean chkParenthesis(String A, int n) {
        Stack<Character> stack=new Stack<Character>();
        boolean flag=true;
        for(int i=0;i<n&&flag;i++){          
            if(A.charAt(i)=='('){
                stack.push(A.charAt(i));
            }
            if(A.charAt(i)==')'){
                if(stack.isEmpty()){
                    flag=false;
                }
                else{
                    stack.pop();
                }               
            }
          }
        if(!stack.isEmpty()){
                flag=false;
            }
        return flag;
        
    }
}


发表于 2017-12-21 17:13:26 回复(0)
参考上面的答案写的,
import java.util.*;
public class Parenthesis {
    public boolean chkParenthesis(String A, int n) {
        // write code here
        Stack s = new Stack() ;
        char c = A.charAt(0);
        if(n % 2 != 0){
            return false ;
        }
        if(A.charAt(0) != '(' || A.charAt(n - 1) != ')'){
            return false ;
        }
        for(int i = 0; i < n; i ++){
            c = A.charAt(i) ;
            if(c == '('){
                //将左括号入栈
                s.push(c) ;
            }else if(c == ')'){  
                if(!s.isEmpty()){
                   s.pop() ;    
                }else{  //因为A可能是类似这样的:“()))”
                    return false ;
                }
            }else{ //遇到了除左右括号之外的字符直接返回false
                return false ;
            }
        }
        return s.isEmpty() ;
    }      
}
发表于 2017-05-26 01:16:06 回复(0)
//经典的栈题目
import java.util.*;
import java.util.Stack;
public class Parenthesis {
 public  boolean chkParenthesis(String A, int n) {
		// write code here
		Stack<String> stack = new Stack<String>();
		char[] chars =A.toCharArray();
		for(int i = 0 ; i < chars.length ; i ++){
			if(chars[i]=='('){   //左括号入栈
				stack.add("(");
			}else if(chars[i]==')'){
			    if(!stack.isEmpty()){
			    	stack.pop();  //右括号出栈
			    }else{
			    	return false; //没得出gg
			    }
			}else{
				return false;  //特殊字符gg
			}
		}
		if(!stack.isEmpty()){ //还有左括号gg
			return false;
		}
		return true;       //没问题OK
	}
}

编辑于 2017-03-05 23:29:43 回复(0)