Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use Java to judge the validity of parentheses

Shulou Source: shulou.com Published: 2022-06-01 23:58:22 09月17日 Update

This article introduces the relevant knowledge of "how to use Java to judge the legitimacy of parentheses". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Public class CheckBrackets {public static void main (String [] args) {String str = "() ([{{}}])]"; System.out.println (bracketsValid (str)) } / * judge single parentheses * @ return * / public static boolean bracketValid (String str) {char [] brackets = str.toCharArray (); / / the number of left parentheses to be matched int left = 0 For (char c: brackets) {if ('('= = c) {left++;} else {left--) } if (left < 0) {return false;}} return 0 = = left } / * judge multiple parentheses * @ return * / public static boolean bracketsValid (String str) {Stack left = new Stack (); char [] brackets = str.toCharArray () For (char c: brackets) {/ / left parenthesis stacks if ('('= c | |'{'= = c | |'['= = c) {left.push (c)) } else {/ / closing parentheses and stack top elements match if (! left.empty () & & leftOf (c) = = left.peek ()) {left.pop () } else {return false;}} / / all elements match return left.empty () } static char leftOf (char c) {if (')'= c) {return'(';} if ('}'= c) {return'{;} return'[' This is the end of the content of "how to use Java to judge the legality of parentheses". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Parentheses legality elements content more knowledge practicality achievement next dilemma variety reality situation quantity articles cases editing websites industries Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Huawei MySQL Linux Xiaomi