java - Well Formed String using Stack and HashMap -


examples of formed , not formed strings are:

1.  “a3{dje(dg[ff]k)wa65}”      - formed 2.  “bbb[bm98{wjhg]333}”    - not formed 3.  “cby(ddd(wklp)behop”    - not formed 

supported brackets {}, [] , ()

here trying , it's returning false reason.

import java.util.hashmap; import java.util.map; import java.util.stack;  public class wellformedstringcheck {        public static boolean iswellformed(string input){          if(input == null) return true;          stack<character> stack = new stack<>();          map<character,character> map = new hashmap<character,character>();          map.put('{', '}');         map.put('(', ')');         map.put('[', ']');            for(int = 0 ; < input.length(); i++){                  char s = input.charat(i);                  if(s == '[' || s == '{' || s == '(' )                     stack.push(s);                 if(s == ']' || s == '}' || s == ')'){                      if(stack.isempty()) return false;                      if(map.get(s) != stack.pop()); return false;                   }              }          if(!stack.isempty()) return false;           return true;       }      public static void main(string[] args) {        system.out.println(iswellformed("a3{dje(dg[ff]k)wa65}"));      }  } 

could tell me what's wrong above approach?

you made silly mistake, , built reference maps parentheses, braces, , brackets backwards. here how building map:

map.put('{', '}'); map.put('(', ')'); map.put('[', ']'); 

but looking closing parentheses, braces, , brackets in map, when keys opening characters instead. returning null , causing method return false.

here complete code method:

public static boolean iswellformed(string input) {     if (input == null) return true;      stack<character> stack = new stack<character>();     map<character,character> map = new hashmap<character,character>();      map.put('}', '{');     map.put(')', '(');     map.put(']', '[');      (int i=0; < input.length(); i++) {         char s = input.charat(i);          if (s == '[' || s == '{' || s == '(') {             stack.push(s);         }         if (s == ']' || s == '}' || s == ')') {             if (map.get(s) != stack.pop()) {                 return false;             }         }     }      if (!stack.isempty()) {         return false;     }     else {         return true;     } } 

i tested code change in intellij , seems run without problems.


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -