括号匹配问题

来源:互联网 发布:便携设备数据恢复软件 编辑:程序博客网 时间:2024/04/28 10:32

题目描述

给定一个字符串,其中的字符只包含三种括号:花括号{ }、中括号[ ]、圆括号( ),即它仅由 “( ) [ ] { }”这六个字符组成。设计算法,判断该字符串是否有效,即字符串中括号是否匹配。括号匹配要求括号必须以正确的顺序配对,如 “{ [ ] ( )}”  “[ ( { } [ ] ) ]”等为正确的格式,而 “[ ( ] )”  “{ [ ( ) }”  “( { } ] )” 均为不正确的格式。

输入描述

Input: {[]()}     []()}

输出描述

Output: true     false

分析

对字符串进行遍历,左括号进栈,之后对右括号进行判断,弹出栈顶元素和右括号的元素进行匹配判断,如果相等,对后一个元素继续判读,如果全都匹配,那么栈为空,输出true,否则输出false。

代码

import java.util.Scanner;
import java.util.Stack;
public class main1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s=sc.next();
char c[]=s.toCharArray();
sc.close();
Stack<Character> st=new Stack<Character>();
for(int i=0; i<c.length;i++)
if(c[i]=='('||c[i]=='['||c[i]=='{')
{
st.push(c[i]);
}
else if(c[i]==')'&& st.peek()=='(')
{
st.pop();
}
else if(c[i]==']'&& st.peek()=='[')
{
st.pop();
}

else if(c[i]=='}'&& st.peek()=='{')
{
st.pop();
}
            if(st.isEmpty())
            {
            System.out.println("true");
            }
            else
            {
            System.out.println("false");
            }
}
}


原创粉丝点击