Hey, Guys. Today i will show you how you can reverse a string using stack.
In this problem we are given a single string and we have to reverse it using stack.
Solution
public String reverse(String str) { Stack<Character> stack = new Stack<>(); for (int i = 0; i < str.length(); i++) { stack.push(str.charAt(i)); } char[] arr = new char[stack.size()]; int i = 0; while (!stack.empty()) { arr[i] = (char) stack.pop(); i++; } return new String(arr); }
Hope this helps you. Thank you ❤.
Top comments (0)