Thursday, March 17, 2022

Reverse a string using Stack GFG Solution

 Reverse a string using Stack 

Easy 

You are given a string S, the task is to reverse the string using stack.

 

Example 1:

Input: S="GeeksforGeeks"
Output: skeeGrofskeeG

 

Your Task:
You don't need to read input or print anything. Your task is to complete the function reverse() which takes the string as an input parameter and returns the reversed string.

 

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)

 

Constraints:
1 ≤ length of the string ≤ 100

Practice Here:

Parenthesis Checker | Practice | GeeksforGeeks


Solution:


class Solution

{

    public:

    //Function to check if brackets are balanced or not.

    bool ispar(string x)

    {

        // Your code here

        stack<char> st;

        for(char c: x)

        {

            if(c=='('||c=='{'||c=='[')

            st.push(c);

            else {

                if(st.empty())

                return false;

                if((c==')'&&st.top()=='(')||(c=='}'&&st.top()=='{')||(c==']'&&st.top()=='['))

                st.pop();

                else return false;

            }

        }

        

       return st.empty();

    }


};

No comments:

Implement stsStr Leetcode solution

  28.   Implement strStr() Easy Implement  strStr() . Given two strings  needle  and  haystack , return the index of the first occurrence of...