括号/括号匹配使用堆栈算法

编程入门 行业动态 更新时间:2024-10-09 05:25:28
本文介绍了括号/括号匹配使用堆栈算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

例如,如果括号/括号在以下内容中匹配:

For example if the parenthesis/brackets is matching in the following:

({}) (()){}() ()

依此类推,但如果括号/括号不匹配它应该返回false,例如:

and so on but if the parenthesis/brackets is not matching it should return false, eg:

{} ({}( ){}) (()

依此类推。请查看此代码?谢谢事先。

and so on. Can you please check this code? Thanks in advance.

public static boolean isParenthesisMatch(String str) { Stack<Character> stack = new Stack<Character>(); char c; for(int i=0; i < str.length(); i++) { c = str.charAt(i); if(c == '{') return false; if(c == '(') stack.push(c); if(c == '{') { stack.push(c); if(c == '}') if(stack.empty()) return false; else if(stack.peek() == '{') stack.pop(); } else if(c == ')') if(stack.empty()) return false; else if(stack.peek() == '(') stack.pop(); else return false; } return stack.empty(); } public static void main(String[] args) { String str = "({})"; System.out.println(Weekly12.parenthesisOtherMatching(str)); }

推荐答案

你的代码在处理'{'和'}'字符时有些混乱。它应该与你处理'('和')'的方式完全平行。

Your code has some confusion in its handling of the '{' and '}' characters. It should be entirely parallel to how you handle '(' and ')'.

此代码稍微修改后,似乎工作正常:

This code, modified slightly from yours, seems to work properly:

public static boolean isParenthesisMatch(String str) { if (str.charAt(0) == '{') return false; Stack<Character> stack = new Stack<Character>(); char c; for(int i=0; i < str.length(); i++) { c = str.charAt(i); if(c == '(') stack.push(c); else if(c == '{') stack.push(c); else if(c == ')') if(stack.empty()) return false; else if(stack.peek() == '(') stack.pop(); else return false; else if(c == '}') if(stack.empty()) return false; else if(stack.peek() == '{') stack.pop(); else return false; } return stack.empty(); }

更多推荐

括号/括号匹配使用堆栈算法

本文发布于:2023-11-29 02:27:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644934.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:括号   堆栈   算法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!