Given a string str, the task is to extract the substrings present between two delimiters, i.e. ‘[‘ and ‘]’. Examples:
Stack-based Approach: Iterate over the characters of the string and insert the index of every ‘[‘ encountered into the stack. For every ‘]’ encountered, simply pop the index stored at the top of the stack and print the substring lying in between. Below is the implementation of the above approach
Output: This is first This is second Time Complexity: O(N) Space-Efficient Approach: The idea is to use Regular Expressions to solve this problem. Create a regular expression to extract the string between two delimiters as regex = “\\[(.*?)\\]” and match the given string with the Regular Expression. Print the subsequence formed. Below is the implementation of the above approach:
Output: This is first This is second Time Complexity: O(N) Practice Tags : |