Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to judge whether a string is legal in Stack

Shulou Source: shulou.com Published: 2022-06-02 05:51:52 09月13日 Update

This article will explain in detail how to judge whether the string is legal in Stack, and the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.

To judge whether a string is legal is like this: if there is a string that contains only braces, then the symbol ([)] is illegal, and the legal symbol should be like this: ([]). Similarly ([]) {such symbols are also illegal based on the above consensus, let's first consider the use of arrays to analyze.

Define an initial value, if the initial input is (or {or [, then we can't immediately determine that it's illegal, because it needs to wait for a match, and if it doesn't match in the end, it's illegal; if you enter it at the beginning) or} or], we can immediately know that it's illegal.

If you enter (and [, the initial value should be + +, then the symbol on the right should be] instead of), you need to determine whether the third input character matches the second character. Only after the second character also matches, it is necessary to match the first character.

If the match is successful, the initial value should-- after all the strings have been matched, you need to see whether the initial value is the value originally assigned. If so, it means that all the symbols are legal, otherwise it means that there are still symbols that do not match. After such analysis, it should be easier to write code. For example, we can achieve this:

/ * *

* determine whether the string is legal

* for example: "([)]" is illegal, "[()]" is legal.

, /

Public class IsValidString {

Public static void main (String [] args) {

/ / define the contents of the string

String symbol= "([]) {"

/ / call the judgment method

Boolean result=isValid (symbol)

System.out.print (result)

}

Public static boolean isValid (String s) {

/ / used to receive incoming values

Char [] arr = s.toCharArray ()

/ / define an array to hold the incoming string with a length of the value of the passed string

Char [] stack = new char [s.length ()]

/ / define stackEnd as-1 so that the first element can enter the array, that is, the stackEnd++ value is 0.

Int stackEnd=-1,length=s.length ()

For (int iTuno Bandi)

Tags: Symbols characters strings legal arrays inputs contents that is parentheses methods code elements articles more knowledge articles square brackets analysis good clever Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn MySQL Docker macOS Redmi