REVERSE STRING USING STACK in java

REVERSE STRING USING STACK in java

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

Input

line 1: contains a string s.

Output

Print a resulting string which is reverse of the original string.

Constraints

1<=s.length()<=100

Expected Time Complexity: O(N)

Expected Space Complexity: O(N)

Sample Input

abcd

Sample Output

dcba

Solution of REVERSE STRING USING STACK in java:–

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
 
        String s = input.next();
        int n = s.length();
 
        Stack<Character> stack = new Stack<>();
 
        for(int i = 0; i < n; i++){
            stack.push(s.charAt(i));
        }
 
        StringBuilder t = new StringBuilder();
        String str = "";
        while(stack.size() > 0){
            //t.append(stack.peek());  we can also use string builder
            str += stack.peek();
            stack.pop(); 
        }
        // System.out.println(t.toString());
        System.out.println(str);
    }
}
 

Add a Comment

Your email address will not be published. Required fields are marked *