字符串——判断一个括号字符串是否匹配

xiaoxiao2021-02-28  65

时间复杂度为O(N),空间复杂度为O(1),代码为isMatch函数

类似的题目:

从键盘读入一个字符串,其中只含有() {} [ ] ,判断该字符串中的每种括号是否成对出现。

提示:可借助栈来实现,括号必须配对出现,如()[ ]{},这是匹配的括号,如([{])},这是不匹配的括号(中间无空格)。

(isMatch_2函数))

思路:

1. 括号匹配的四种可能性:

①左右括号配对次序不正确 ②右括号多于左括号 ③左括号多于右括号 ④左右括号匹配正确 2. 算法思想: 1.顺序扫描算数表达式(表现为一个字符串),当遇到三种类型的左括号时候让该括号进栈; 2.当扫描到某一种类型的右括号时,比较当前栈顶元素是否与之匹配,若匹配,退栈继续判断; 3.若当前栈顶元素与当前扫描的括号不匹配,则左右括号配对次序不正确,匹配失败,直接退出; 4.若字符串当前为某种类型的右括号而堆栈已经空,则右括号多于左括号,匹配失败,直接退出; 5.字符串循环扫描结束时,若堆栈非空(即堆栈尚有某种类型的左括号),则说明左括号多于右括号,匹配失败;

6.正常结束则括号匹配正确。

public class KuoHaoMatch { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(isMatch("()")); System.out.println(isMatch("(())")); System.out.println(isMatch("())")); System.out.println(isMatch("()(")); System.out.println(isMatch_2("{}{][")); System.out.println(isMatch_2("()[]{}")); System.out.println(isMatch_2("(([{}]))")); System.out.println(isMatch_2("([{])}")); System.out.println(isMatch_2("([{}])))")); } //一种括号匹配 public static boolean isMatch(String s){ if(s.length()==0||s==null) return false; int num=0; //左括号和右括号出现次数的差值 char[] ch=s.toCharArray(); for(int i=0;i<ch.length;i++){ if(ch[i]=='(') num++; if(ch[i]==')') num--; if(num<0) return false; } if(num==0) return true; return false; } //三种括号匹配 public static boolean isMatch_2(String s){ Stack<Character> stack=new Stack<Character>(); char[] ch=s.toCharArray(); for (int i = 0; i < ch.length; i++) { if (ch[i] == '(' || ch[i] == '{' || ch[i] == '[') { stack.push(ch[i]); } else if(stack.isEmpty()) //必须加上这两行,不然后面会抛出空栈异常 return false; else if(ch[i]==')'&& stack.peek()=='('||ch[i]=='}'&&stack.peek()=='{' ||ch[i]==']'&&stack.peek()=='[') stack.pop(); else return false; } if(!stack.isEmpty()) return false; return true; } }

转载请注明原文地址: https://www.6miu.com/read-70521.html

最新回复(0)