Reverse A String Using Stack Geeks For Geeks

 Problem Link:


https://practice.geeksforgeeks.org/problems/reverse-a-string-using-stack/1


It is also the problem of the day.


Solution:

class Solution {

    

    public String reverse(String s){

        Stack<Character>stack=new Stack<Character>();

        for(int i=0;i<s.length();i++){

            stack.push(s.charAt(i));

        }

        StringBuilder sb=new StringBuilder();

        while(!stack.isEmpty()){

            sb.append(stack.pop());

        }

        return sb.toString();

    }


}



Time Complexity: O(N)[GFG Time:0.2/1.5]

Space Complexity: O(1)

Auxiliary Space: O(N)[Stack Of n character is used.]

Approach Used:

Here we will use an approach that will add all elements of string into the stack.

Later we will use a StringBuilder object and all the characters into it after emoving them from the stack.

Since Stack works on Last In First Out it will automatically reverse the string and StringBuilder.toString() will give us the desired string as output.


Total Test Cases:300



"Thanks For Reading.😇"

"Share Further To Increase Knowledge Treasure.😊"

Comments

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks