Reverse A String Using Stack Geeks For Geeks
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));
}
StringBuffer sb=new StringBuffer();
while(!stack.isEmpty()){
sb.append(stack.pop());
}
String s1=sb.toString();
return s1;
}
}
Approach:
We will add all the elements of the given string into the stack. After that, we will apply a while loop which will run till the stack becomes empty and the object of StringBuffer will append those characters.
In the end, we will convert the string buffer object to a string.
TIME: O(N) [here N is the length of given string][GFG time: 0.2/1.5]
SPACE: O(1) [here we are simply appending the characters in the last and later converting object of StringBuffer into a string.]
Thanks for Reading 😇.
Comments
Post a Comment