Pages

Friday, September 19, 2025

Reverse a string using Stack

 import java.util.*;


// Push element at the bottom of stack

class StackB {

    

    public static String reverseString(String str) {

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

        int idx = 0;

        while(idx < str.length()) {

            s.push(str.charAt(idx));

            idx++;

        }

        

        

        StringBuilder result = new StringBuilder("");

        while(!s.isEmpty()) {

            char curr = s.pop();

            result.append(curr); // append adds to the last

        }

        

        return result.toString();

    }

    

    public static void main(String[] args) {

        String str = "abc";

        String result = reverseString(str);

        

        System.out.println(result);

        

    }

}


No comments:

Post a Comment

Contains duplicate - using HashSet (optimized code)

  class Solution {     public boolean containsDuplicate ( int [] nums) {         HashSet< Integer > seen = new HashSet<>()...