首页 > 试题广场 >

检查给定字符串中的多种括号是否匹配

[编程题]检查给定字符串中的多种括号是否匹配
  • 热度指数:336 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定字符串,检查其中的括号是否匹配(可能出现的括号包括大括号,中括号和小括号),所谓匹配是指:
1. 左右括号应该一一对应,例如:abc(lasdf[lsdf]lasdf,少了一个右小括号,不匹配。
2. 左括号应该出现在对应的右括号的左边,例如:abc)sdf{lkjsdf}sdf(,第一个右小括号前没有左小括号,不匹配。
3. 一对括号之间的字符串,如果出现括号,那么这些括号也必须匹配,例如:abc(dl[lksdflksd)xd],小括号中出现了一个左中括号(没有对应的右中括号),不匹配

匹配的例子为:abc(dl[lksdf]lksd),左括号和右括号一一对应,因此匹配

当字符串中括号匹配时,输出字符串:true;如果不匹配,输出字符串:false

输入描述:
一行字符串


输出描述:
如果字符串中括号匹配,那么输出:true
如果不匹配,那么输出:false
示例1

输入

abc(dl[lksdf]lksd)

输出

true
function strMatch(str){
    let stack =[];
    let topElem;
    let i;
    for (i=0;i<str1.length;i++){
        if(str[i]=="("||str[i]=="["||str[i]=="{"){
            stack.push(str[i]);
        }else{ 
            if((str[i]==")"||str[i]=="}"||str[i]=="]")&&stack.length==0)
            return false;
            if(str[i]==")"||str[i]=="}"||str[i]=="]")
            topElem=stack.pop();
            if(str[i] == ')' && topElem != '(' )
            return false;
            if(str[i] == ']' && topElem != '[' )
            return false;
            if(str[i] == '}' && topElem != '{' )
            return false;       
        }
    }
    return stack.length == 0 ? true : false;
}
let str1 = readline();
console.log(strMatch(str1));


编辑于 2022-03-29 21:30:30 回复(0)
#include <bits/stdc++.h>
using namespace std;
int main()
{
    string str;
    cin >> str;
    int n = str.size();
    stack<char> s;
    bool fault = false;
    for(int i = 0;i < n;i++)
    {
        if(str[i] == '{' || str[i] == '[' || str[i] == '(')
            s.push(str[i]);
        else if(str[i] == '}' || str[i] == ']' || str[i] == ')')
        {
            if(str[i] == '}')
            {
                if(s.size() && s.top() == '{')
                    s.pop(); 
                else
                    fault = true;
            }else if(str[i] == ']')
            {
                if(s.size() && s.top() == '[')
                    s.pop(); 
                else
                    fault = true;
            }else if(str[i] == ')')
            {
                if(s.size() && s.top() == '(')
                    s.pop(); 
                else
                    fault = true;
            }
        }
    }
    if(!s.empty() || fault)
    {
        cout << "false" << endl;
    }else
        cout << "true" << endl;
    return 0;
}

发表于 2022-03-16 17:17:54 回复(0)
#include <iostream>
#include<cstring>
#include <cstdio> // 相当于C语⾔⾥⾯的#include <stdio.h>
#include <cstdlib> // 相当于C语⾔⾥⾯的#include <stdib.h>
#include <cctype> // 相当于C语⾔⾥⾯的#include <ctype.h>
#include <cstring>
#include <algorithm>
#include <stack>
#include<queue>
#include<map>
#include<vector>
#include<stack>
#include<cstdbool>
using namespace std;
stack<char>a;
string b;
bool check(string b){
    for(string::iterator it=b.begin();it!=b.end();++it){
        if(*it=='<'){
            char e=(*it);
            a.push(e);
        }
        if(*it=='('){
           char e=(*it);
            a.push(e);
        }
        if(*it=='{'){
           char e=(*it);
            a.push(e);
        }
        if(*it=='['){
           char e=(*it);
            a.push(e);
        }
        if(*it=='>'){
            if(!a.empty()&&a.top()=='<')
                a.pop();
            else
                return false;
        }
        if(*it=='}'){
            if(!a.empty()&&a.top()=='{')
                a.pop();
            else
                return false;
        }
        if(*it==']'){
            if(!a.empty()&&a.top()=='[')
                a.pop();
            else
                return false;
        }
        if(*it==')'){
            if(!a.empty()&&a.top()=='(')
                a.pop();
            else
                return false;
        }
    }
    if(a.empty())
        return true;
    else
        return false;
}
int main(){

    string b;
    getline(cin,b);
    check(b)?cout<<"true":cout<<"false";
return 0;
}

发表于 2022-02-14 10:32:30 回复(1)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
        String nextLine = in.nextLine();
        System.out.println(isRight(nextLine));

    }

    public static boolean isRight(String input) {
        Stack<String> stack = new Stack<String>();
        int len = input.length();
        for (int i = 0; i < len; i++) {
            String str_ch = input.charAt(i) + "";
            if (str_ch.equals("(")) {
                stack.push(str_ch);
            } else if (str_ch.equals("[")) {
                stack.push(str_ch);
            } else if (str_ch.equals("{")) {
                stack.push(str_ch);
            } else if (str_ch.equals(")")) {
                if(stack.empty())
                    return false;
                if (stack.peek().equals("(")) {
                    stack.pop();
                }
            } else if (str_ch.equals("]")) {
                if(stack.empty())
                    return false;
                if (stack.peek().equals("[")) {
                    stack.pop();
                }
            } else if (str_ch.equals("}")) {
                if(stack.empty())
                    return false;
                if (stack.peek().equals("{")) {
                    stack.pop();
                }
            }
        }
        if (stack.empty())
            return true;
        return false;
    }
}


编辑于 2021-04-10 19:13:31 回复(0)

import java.util.Scanner;
import java.util.Stack;
import java.util.*;
import java.lang.*;

public class Main { 
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        String s=sc.nextLine();
        System.out.println(parenMatch(s));
    }
public static boolean parenMatch(String s) {
        Stack S = new Stack();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i)=='('||s.charAt(i)=='{' || s.charAt(i)=='['){
                S.push(s.charAt(i));
            }
            else if(s.charAt(i)==')'){
                if (S.isEmpty()) return false;
                if ((char)S.pop()!='(')return false;
            }
            else if(s.charAt(i)==']'){
                if (S.isEmpty()) return false;
                if ((char)S.pop()!='[')return false;
            }
            else if(s.charAt(i)=='}'){
                if (S.isEmpty()) return false;
                if ((char)S.pop()!='{')return false;
            }

            
            
        
        }
        if (S.empty()){
            return true;
        }else{
            return false;
        }
}
    
}

发表于 2021-03-17 17:05:53 回复(1)