Reverse Words In A Given String Geeks For Geeks
Problem Link:
Its also Problem Of Day 29 January
https://practice.geeksforgeeks.org/problems/reverse-words-in-a-given-string5459/1
Solution:
class Solution
{
//Function to reverse words in a given string.
String reverseWords(String s)
{
StringBuilder sb=new StringBuilder();
Stack<String>stack=new Stack<String>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='.'){
stack.add(sb.toString());
sb.setLength(0);
}
else{
sb.append(s.charAt(i));
}
}
stack.add(sb.toString());
sb.setLength(0);
while(!stack.isEmpty()){
sb.append(stack.pop());
sb.append('.');
}
sb.setLength(sb.length()-1);
return sb.toString();
}
}
Time Complexity: O(String Length)[GFG Time:0.7/1.8]
Space Complexity: O(1)[Only A String is used. Not any array.]
Auxillary Space:[Stack is used which will store all strings separated by dots(.).][O(String Length-Number of dots)].
Total Test Cases:118
Approach:
We use approaches of storing strings before dots.
We will traverse the string and continuously append it on the characters in StringBuilder till the dot comes.
If a dot comes then we will convert the StringBuilder object to string and add that StringBuilder object into the stack and make it empty for a fresh start.
Now again we will start iterations fill up StringBuilder and simultaneously add into the stack.
After we are finished with traversal we will pop out the stack and along with that add . in StringBuilder.
(The problem will be a dot will also be present with the last string, for that remove the last character or decrease the length of StringBuilder by 1 and return in form of string.)
eg
string is "we.are.learning.to.code"
Stringbuilder object be sb and Stack be stack
we start taversing the string:
sb.append(w)
sb.append(e)
now dot arrives
stack.push(sb.toString())
sb.setLength(0)//clear sb
now again sb.append(a)
.
.
.
.
This will go till last and that stage sb will be having value "code"
Now we will also store this in a stack and make sb empty.
Its time for traversal of stack till it become emoty and simulatanoesut append in sb.
eg
sb.append(stack.pop())// sb=code
sb.append('.')//sb=code.
In such a way after stack becomes empty sb will be
sb=code.to.learn.are.we.
Hereafter one additional dot is coming which will remove by reducing the size of sb by 1.
and now return sb.toString();
"Thanks For Reading.😇"
"Share Further To Increase Knowledge.😊"
Comments
Post a Comment