java - Checking if the given String has equally matching parenthesis -


found interesting problem solving questions online , here is.

you check given string str if contains matching parenthesis. 

example input: [ ] , [ ( ] ) , { [ ] } , { [ } ] , { [ } ) , { ] }

example output: equal, equal, equal, equal, not equal, not equal

i have managed complete requirements feature using basics, wondering if there better way of doing it?

string str = "{[(])}(){}";     int pairs = 0;     boolean unabletofind = false;     arraylist<character> anchar = new arraylist<character>();      (int = 0; < str.length(); i++) {         anchar.add(str.charat(i));     }      if (str.length() % 2 == 0) {          while (pairs != str.length() / 2) {             (int = 1; < anchar.size(); i++) {                 char = (char) anchar.get(0);                 char b = (char) anchar.get(i);                 if (a == '{' && b == '}' || == '[' && b == ']' || == '(' && b == ')') {                     anchar.remove(i);                     anchar.remove(0);                     pairs++;                     break;                 } else {                     if (i == anchar.size() - 1) { // reached end of array                         unabletofind = true;                         break;                     }                 }             }             if (unabletofind)                 break;         }          if (pairs == str.length() / 2) {             system.out.println("log#01: string have balanced parenthesis");         } else {             system.out.println("log#02: string not have balanced parenthesis. (" + pairs + "/" + str.length() / 2 + " pairs found)");         }     } else {         system.out.println("log#03: string not have numbers of parenthesis");     } 

your approach overly complex. need 3 counters - countround, countsquare, , countcurly. initialize 3 zero, walk string character-by-character. if see opening parentheses, increment counter; if closing parentheses, decrement corresponding counter. once loop over, 3 counters must @ zero; otherwise numbers of parentheses not match up.

note: not check parentheses balanced, because example not require (i.e. "[(])" produces "equal" through input unbalanced).


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -