Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

php - How to check if parentheses are balanced?

Write a function called validBraces that takes a string of braces, and determines if the order of the braces is valid. validBraces should return true if the string is valid, and false if it's invalid.

All input strings will be nonempty, and will only consist of open parentheses (, closed parentheses ), open brackets [, closed brackets ], open curly braces { and closed curly braces }.

What is considered Valid?

A string of braces is considered valid if all braces are matched with the correct brace. For example:

(){}[] and ([{}]) would be considered valid, while (}, [(]), and [({})](] would be considered invalid.

Specification
validBraces(braces)

Checks if the brace order is valid

Parameters
braces: String - A string representation of an order of braces

Return Value
Boolean - Returns true if order of braces are valid

Examples:

    Input   Output
validBraces( "(){}[]" )     true
validBraces( "(}" )         false
validBraces( "[(])" )       false
validBraces( "([{}])" )     true
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is pretty trivial assignment and you can use stack (i.e. array/list). You then iterate over input string char by char and once you detect opening bracket ((, <, { etc) you push that bracket on your stack (or append to the array, does not matter). And when you encounter closing bracket (), >, } etc) then you pop last element from your stack. You then check if bracket type matches so when you have > then you should have popped < from your stack otherwise you stop the process complaining about mismatched brackets (or whatever). Once you done iterating without any errors your stack should be empty. You can use counter/flag if you need to know if there were any brackets processed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...