Back to Browse

How to find Balanced Parenthesis | Interview Program 3

219 views
Dec 6, 2024
12:09

๐…๐ข๐ง๐๐ข๐ง๐  ๐๐š๐ฅ๐š๐ง๐œ๐ž๐ ๐๐š๐ซ๐ž๐ง๐ญ๐ก๐ž๐ฌ๐ข๐ฌ: 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 formats

No download links available.

How to find Balanced Parenthesis | Interview Program 3 | NatokHD