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

Perfect Sum Problem Geeks for Geeks

Array Formation HackerEarth

Recursive Sequence Geeks For Geeks Problem Of The Day 12-02-2024