Check whether string of braces, brackets, and parentheses is balanced The 2019 Stack Overflow Developer Survey Results Are InBalanced parenthesesCheck for balanced parenthesesBalance braces methodChecking for balanced parenthesesBalanced bracesSwift HackerRank Balanced BracketsCheck for balanced parentheses in JavaScriptCheck balanced brackets in a textCheck if brackets are balancedLeetcode: Valid parentheses

APIPA and LAN Broadcast Domain

Is it okay to consider publishing in my first year of PhD?

Slides for 30 min~1 hr Skype tenure track application interview

Falsification in Math vs Science

How can I define good in a religion that claims no moral authority?

Straighten subgroup lattice

Output the Arecibo Message

Cooking pasta in a water boiler

If I can cast sorceries at instant speed, can I use sorcery-speed activated abilities at instant speed?

What is the motivation for a law requiring 2 parties to consent for recording a conversation

Merge two greps into single one

How do I free up internal storage if I don't have any apps downloaded?

Why doesn't UInt have a toDouble()?

How to display lines in a file like ls displays files in a directory?

How to type a long/em dash `—`

Why does the nucleus not repel itself?

Dropping list elements from nested list after evaluation

Is it possible for absolutely everyone to attain enlightenment?

Why isn't the circumferential light around the M87 black hole's event horizon symmetric?

Is it safe to harvest rainwater that fell on solar panels?

Star Trek - X-shaped Item on Regula/Orbital Office Starbases

Flight paths in orbit around Ceres?

What is the most efficient way to store a numeric range?

What is the meaning of Triage in Cybersec world?



Check whether string of braces, brackets, and parentheses is balanced



The 2019 Stack Overflow Developer Survey Results Are InBalanced parenthesesCheck for balanced parenthesesBalance braces methodChecking for balanced parenthesesBalanced bracesSwift HackerRank Balanced BracketsCheck for balanced parentheses in JavaScriptCheck balanced brackets in a textCheck if brackets are balancedLeetcode: Valid parentheses



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2












$begingroup$


The Task



is taken from codewars:




Write a function that takes a string of braces, and determines if the
order of the braces is valid. It 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
parentheses, brackets and curly braces: ()[].



What is considered Valid? A string of braces is considered valid if
all braces are matched with the correct brace.



Examples




  • ()[] => True


  • ([]) => True


  • (} => False


  • [(]) => False


  • [()](] => False



My solution



const areBracesBalanced = brc => {
const brace = Object.freeze({
"(": [],
"[": [],
"": [],
);

const removeBrace = b => brace[b].splice(-1, 1);
const getLastBraceIndex = b => brace[b][brace[b].length - 1]
const braceExists = b => !brace[b].length;
const isBraceBeforeClosed = (before, current) => braceExists(before) || getLastBraceIndex(before) < getLastBraceIndex(current);

const braceIsBalanced = (b, i) => {
switch (b) {
case "(":
case "[":
case "{":
return brace[b].push(i);
case ")":
return isBraceBeforeClosed("[", "(") &&
isBraceBeforeClosed(" 













2












$begingroup$


The Task



is taken from codewars:




Write a function that takes a string of braces, and determines if the
order of the braces is valid. It 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
parentheses, brackets and curly braces: ()[].



What is considered Valid? A string of braces is considered valid if
all braces are matched with the correct brace.



Examples




  • ()[] => True


  • ([]) => True


  • ( => False


  • [(]) => False


  • [()](] => False



My solution



const areBracesBalanced = brc => {
const brace = Object.freeze({
"(": [],
"[": [],
"": [],
);

const removeBrace = b => brace[b].splice(-1, 1);
const getLastBraceIndex = b => brace[b][brace[b].length - 1]
const braceExists = b => !brace[b].length;
const isBraceBeforeClosed = (before, current) => braceExists(before) || getLastBraceIndex(before) < getLastBraceIndex(current);

const braceIsBalanced = (b, i) => {
switch (b) {
case "(":
case "[":
case "improve this answer











$endgroup$



I'm not very good at Javascript, but I do know how to make an algorithm.



In the code below I use the fact that correct or [] or () will always touch and can be removed. Just taken these away until there aren't any left and if you've got an empty string it was balanced, if it is not empty then clearly it must be unbalanced.



function isBalanced(input)

while (input.length > 0)
var output = input.replace("", "").replace("[]", "").replace("()", "");
if (input == output) return false;
input = output;

return true;


function test(input)

alert("'"+input+"' = "+(isBalanced(input) ? "Correct" : "Incorrect"));


test("()[]");
test("([])");
test("(");
test("[(])");
test("[()](]");
test("()[]");


Someone with a bit more knowledge of Javascript might be able to further optimize this code.



To make it slightly more efficient there's a version with a regular expression:



function isBalanced(input)

while (input.length > 0) []/, "");
if (input == output) return false;
input = output;

return true;



I think this short code is elegant, but here it is somewhat at the expense of clarity.







share|improve this answer














share|improve this answer



share|improve this answer








edited 58 mins ago

























answered 3 hours ago









KIKO SoftwareKIKO Software

1,722512




1,722512











  • $begingroup$
    I don't see why your suggested algorithm is better than the original code, and you haven't told us why. Repeated string replacement is a poor strategy for performance.
    $endgroup$
    – 200_success
    3 hours ago










  • $begingroup$
    @200_success I'm sorry, I didn't know I had to explain that, and as I pointed out, I am not a Javascript expert.
    $endgroup$
    – KIKO Software
    3 hours ago











  • $begingroup$
    @200_success I saw it as a coding challenge, I'm sorry. Still think that it is a clear and, above all, comprehensible answer.
    $endgroup$
    – KIKO Software
    3 hours ago
















  • $begingroup$
    I don't see why your suggested algorithm is better than the original code, and you haven't told us why. Repeated string replacement is a poor strategy for performance.
    $endgroup$
    – 200_success
    3 hours ago










  • $begingroup$
    @200_success I'm sorry, I didn't know I had to explain that, and as I pointed out, I am not a Javascript expert.
    $endgroup$
    – KIKO Software
    3 hours ago











  • $begingroup$
    @200_success I saw it as a coding challenge, I'm sorry. Still think that it is a clear and, above all, comprehensible answer.
    $endgroup$
    – KIKO Software
    3 hours ago















$begingroup$
I don't see why your suggested algorithm is better than the original code, and you haven't told us why. Repeated string replacement is a poor strategy for performance.
$endgroup$
– 200_success
3 hours ago




$begingroup$
I don't see why your suggested algorithm is better than the original code, and you haven't told us why. Repeated string replacement is a poor strategy for performance.
$endgroup$
– 200_success
3 hours ago












$begingroup$
@200_success I'm sorry, I didn't know I had to explain that, and as I pointed out, I am not a Javascript expert.
$endgroup$
– KIKO Software
3 hours ago





$begingroup$
@200_success I'm sorry, I didn't know I had to explain that, and as I pointed out, I am not a Javascript expert.
$endgroup$
– KIKO Software
3 hours ago













$begingroup$
@200_success I saw it as a coding challenge, I'm sorry. Still think that it is a clear and, above all, comprehensible answer.
$endgroup$
– KIKO Software
3 hours ago




$begingroup$
@200_success I saw it as a coding challenge, I'm sorry. Still think that it is a clear and, above all, comprehensible answer.
$endgroup$
– KIKO Software
3 hours ago

















draft saved

draft discarded
















































Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217275%2fcheck-whether-string-of-braces-brackets-and-parentheses-is-balanced%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

格濟夫卡 參考資料 导航菜单51°3′40″N 34°2′21″E / 51.06111°N 34.03917°E / 51.06111; 34.03917ГезівкаПогода в селі 编辑或修订