Wednesday, July 3, 2019

Reverse a string using Stack

Problem Statement:



An string of words is given, the task is to reverse the string using stack.
Input Format:
The first line of input will contains an integer T denoting the no of test cases . Then T test cases follow. Each test case contains a string s of words without spaces.
Output Format:
For each test case ,print the reverse of the string in new line. 

Your Task:
Since this is a function problem, you don't need to take any input. Just complete the provided function.
Constraints:
1 <= T <= 100
1 <= length of the string <= 100

Example:
Input:
2
MuscleJava
CodeJavaMuscle

Output:
avaJelcsuM
elcsuMavaJedoC


Solution:

public class MuscleJava
{
    public void reverse(String str)
    {
       Stack<Character> st = new Stack();
       for(int i=0; i<str.length(); i++)
       {
           st.push(str.charAt(i));
       }
       while(st.size() > 0 )
        {
            System.out.print(st.pop());
        }
        System.out.println();
    }
    public static void main (String[] args)
    {
        Scanner s = new Scanner(System.in);
        int t = s.nextInt();
         for(int k=0;k < t; k++)
         {
             String in = s.next();
             reverse(in);
         }
    }

No comments:

Post a Comment