How to find Balanced Parenthesis | Interview Program 3
๐ ๐ข๐ง๐๐ข๐ง๐ ๐๐๐ฅ๐๐ง๐๐๐ ๐๐๐ซ๐๐ง๐ญ๐ก๐๐ฌ๐ข๐ฌ: interesting question ๐๐ซ๐จ๐๐ฅ๐๐ฆ: we will be give a string as follows String parenthesis = "{[()]}"; String parenthesis = "}]()]}"; We need to find out whether the string has balanced parenthesis or not? What does it mean by ๐๐๐ฅ๐๐ง๐๐๐ ๐ฉ๐๐ซ๐๐ง๐ญ๐ก๐๐ฌ๐ข๐ฌ? Corresponding to each ๐จ๐ฉ๐๐ง๐ข๐ง๐ ๐ฉ๐๐ซ๐๐ง๐ญ๐ก๐๐ฌ๐ข๐ฌ there should be respective ๐๐ฅ๐จ๐ฌ๐ข๐ง๐ ๐ฉ๐๐ซ๐๐ง๐ญ๐ก๐๐ฌ๐ข๐ฌ in the right sequence For Example: this string "{[()]}" has balanced parenthesis while this string "}]()]}" has not balanced parenthesis as it is starting with closing parenthesis ๐๐จ๐ฐ ๐ญ๐จ ๐ฌ๐จ๐ฅ๐ฏ๐ ๐ข๐ญ ๐ฉ๐ซ๐จ๐ ๐ซ๐๐ฆ๐ฆ๐๐ญ๐ข๐๐๐ฅ๐ฅ๐ฒ? We will have to use ๐๐ญ๐๐๐ค/๐๐ซ๐ซ๐๐ฒ๐๐๐ช๐ฎ๐ to solve this. Let us understand step by step: ๐๐ซ๐-๐๐๐ช๐ฎ๐ข๐ฌ๐ข๐ญ๐: we will convert string in to char array and process ๐ฌ๐ญ๐๐ฉ ๐๐ฒ ๐ฌ๐ญ๐๐ฉ Define one boolean flag as true ๐๐ญ๐๐ฉ๐: first we need to look for opening parenthesis. ๐๐ญ๐๐ฉ๐: As soon as we encounter such opening parenthesis we need to put that to on top of stack ๐๐ญ๐๐ฉ๐: Now we will look for closing parenthesis There could be two cases: ๐๐ฌ๐ญ ๐๐๐ฌ๐: we may encounter closing parenthesis in the starting. we will mark boolean flag false ๐๐ง๐ ๐๐๐ฌ๐: we may encounter closing parenthesis after encountering opening parenthesis as per step 1 ๐๐ญ๐๐ฉ๐: If we encounter closing brace as per Case1, we will simply say parenthesis are not balanced While for second case, we will look for respective opening parenthesis from stack top and will clean this opening parenthesis from stack ๐๐ญ๐๐ฉ๐: we will repeat step ๐๐ญ๐๐ฉ๐: At last we will check if stack is empty and boolean flag is true If yes then parenthesis are balanced else not balanced. Regards Prince Kumar
Download
0 formatsNo download links available.