publicstaticStringreverseP(Strings){if(s==null||"".equals(s)){returns;}Stack<String>st=newStack<>();StringBuildermainSb=newStringBuilder();intcounter=0;for(inti=0;i<s.length();i++){if(s.charAt(i)=='('){// push subsequent characters to stack// push opposite brace for ease of character pop and no replacementst.push(")");counter++;}elseif(s.charAt(i)==')'){st.push("(");// pop subsequent characters to stack till you encounter ")" in stack i.e. "(" w.r.t. main stringStringBuildersb1=newStringBuilder();while(!st.isEmpty()){Stringpop=st.pop();sb1.append(pop);if(pop.equals(")")){st.push(sb1.toString());// just till last encounter of opening brace and add that to stackbreak;}}counter--;// if counter is 0 ==> balanced parenthesis,// but stack is still contains elements and need to append to main Stringif(counter==0&&!st.isEmpty()){while(!st.isEmpty()){mainSb.append(st.pop());}}}elseif(!st.isEmpty()){st.push(""+s.charAt(i));}else{mainSb.append(s.charAt(i));}}returnmainSb.toString();}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Java
Not so good solution