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

How do you keep chess fun when your opponent constantly defeats?

How do PCB vias affect signal quality?

Geography at the pixel level

Can a flute soloist sit?

Correct punctuation for showing a character's confusion

What to do when moving next to a bird sanctuary with a loosely-domesticated cat?

Button changing its text & action. Good or terrible?

What is the light source in the black hole images?

Worn-tile Scrabble

Keeping a retro style to sci-fi spaceships?

Deal with toxic manager when you can't quit

Old scifi movie from the 50s or 60s with men in solid red uniforms who interrogate a spy from the past

Can withdrawing asylum be illegal?

What is this business jet?

How to translate "being like"?

Did any laptop computers have a built-in 5 1/4 inch floppy drive?

Straighten subgroup lattice

"as much details as you can remember"

If a sorcerer casts the Banishment spell on a PC while in Avernus, does the PC return to their home plane?

Why didn't the Event Horizon Telescope team mention Sagittarius A*?

Is it correct to say the Neural Networks are an alternative way of performing Maximum Likelihood Estimation? if not, why?

What is this sharp, curved notch on my knife for?

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

Flight paths in orbit around Ceres?



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("improve this question











$endgroup$

















    $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 39 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$
      Well, if you don't say anything about the original code, then it's not a code review, and hence not a valid answer.
      $endgroup$
      – 200_success
      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$
      Well, if you don't say anything about the original code, then it's not a code review, and hence not a valid answer.
      $endgroup$
      – 200_success
      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$
    Well, if you don't say anything about the original code, then it's not a code review, and hence not a valid answer.
    $endgroup$
    – 200_success
    3 hours ago




    $begingroup$
    Well, if you don't say anything about the original code, then it's not a code review, and hence not a valid answer.
    $endgroup$
    – 200_success
    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ГезівкаПогода в селі 编辑或修订