Dada la string str que consta de varias palabras, la tarea es invertir la string completa palabra por palabra.
Ejemplos:
Entrada: str = «I Love To Code»
Salida: Code To Love I
Entrada: str = «estructuras de datos y algoritmos»
Salida: algoritmos y estructuras de datos
Enfoque: este problema se puede resolver no solo con la ayuda de strtok() , sino que también se puede resolver usando Stack Container Class en STL C++ siguiendo los pasos dados:
- Crea una pila vacía.
- Recorra toda la string, mientras recorre agregue los caracteres de la string en una
variable temporal hasta que obtenga un espacio (‘ ‘) y empuje esa variable temporal a la pila. - Repita el paso anterior hasta el final de la string.
- Saque las palabras de la pila hasta que la pila no esté vacía, lo que será en orden inverso.
A continuación se muestra la implementación del enfoque anterior:
C++
//C++ implementation of the above approach #include<bits/stdc++.h> using namespace std; //function to reverse the words //of the given string without using strtok(). void reverse(string s) { //create an empty string stack stack<string> stc; //create an empty temporary string string temp=""; //traversing the entire string for(int i=0;i<s.length();i++) { if(s[i]==' ') { //push the temporary variable into the stack stc.push(temp); //assigning temporary variable as empty temp=""; } else { temp=temp+s[i]; } } //for the last word of the string stc.push(temp); while(!stc.empty()) { // Get the words in reverse order temp=stc.top(); cout<<temp<<" "; stc.pop(); } cout<<endl; } //Driver code int main() { string s="I Love To Code"; reverse(s); return 0; } // This code is contributed by Konderu Hrishikesh.
Java
//Java implementation of // the above approach import java.util.*; class GFG{ // Function to reverse the words // of the given String without // using strtok(). static void reverse(String s) { // Create an empty String stack Stack<String> stc = new Stack<>(); // Create an empty temporary String String temp = ""; // Traversing the entire String for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == ' ') { // Push the temporary // variable into the stack stc.add(temp); // Assigning temporary // variable as empty temp = ""; } else { temp = temp + s.charAt(i); } } // For the last word // of the String stc.add(temp); while(!stc.isEmpty()) { // Get the words in // reverse order temp = stc.peek(); System.out.print(temp + " "); stc.pop(); } System.out.println(); } //Driver code public static void main(String[] args) { String s = "I Love To Code"; reverse(s); } } // This code is contributed by gauravrajput1
Python3
# Python3 implementation of # the above approach # function to reverse the # words of the given string # without using strtok(). def reverse(s): # create an empty string # stack stc = [] # create an empty temporary # string temp = "" # traversing the entire string for i in range(len(s)): if s[i] == ' ': # push the temporary variable # into the stack stc.append(temp) # assigning temporary variable # as empty temp = "" else: temp = temp + s[i] # for the last word of the string stc.append(temp) while len(stc) != 0: # Get the words in reverse order temp = stc[len(stc) - 1] print(temp, end = " ") stc.pop() print() # Driver code s = "I Love To Code" reverse(s) # This code is contributed by divyeshrabadiya07
C#
// C# implementation of // the above approach using System; using System.Collections; class GFG { // Function to reverse the words // of the given String without // using strtok(). static void reverse(string s) { // Create an empty String stack Stack stc = new Stack(); // Create an empty temporary String string temp = ""; // Traversing the entire String for(int i = 0; i < s.Length; i++) { if(s[i] == ' ') { // Push the temporary // variable into the stack stc.Push(temp); // Assigning temporary // variable as empty temp = ""; } else { temp = temp + s[i]; } } // For the last word // of the String stc.Push(temp); while(stc.Count != 0) { // Get the words in // reverse order temp = (string)stc.Peek(); Console.Write(temp + " "); stc.Pop(); } Console.WriteLine(); } // Driver code static void Main() { string s = "I Love To Code"; reverse(s); } } // This code is contributed by divyesh072019
Javascript
<script> // Javascript implementation of // the above approach // Function to reverse the words // of the given String without // using strtok(). function reverse(s) { // Create an empty String stack let stc = []; // Create an empty temporary String let temp = ""; // Traversing the entire String for(let i = 0; i < s.length; i++) { if(s[i] == ' ') { // Push the temporary // variable into the stack stc.push(temp); // Assigning temporary // variable as empty temp = ""; } else { temp = temp + s[i]; } } // For the last word // of the String stc.push(temp); while(stc.length != 0) { // Get the words in // reverse order temp = stc[stc.length - 1]; document.write(temp + " "); stc.pop(); } } let s = "I Love To Code"; reverse(s); </script>
Code To Love I
Complejidad de tiempo: O(N)
Otro enfoque: aquí se analiza un enfoque sin usar la pila . Este problema también se puede resolver usando la pila siguiendo los pasos a continuación:
- Crea una pila vacía.
- Tokenize la string de entrada en palabras usando espacios como separador con la ayuda de strtok()
- Empuje las palabras en la pila.
- Saque las palabras de la pila hasta que la pila no esté vacía, lo que será en orden inverso.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to reverse the words // of the given sentence void reverse(char k[]) { // Create an empty character array stack stack<char*> s; char* token = strtok(k, " "); // Push words into the stack while (token != NULL) { s.push(token); token = strtok(NULL, " "); } while (!s.empty()) { // Get the words in reverse order cout << s.top() << " "; s.pop(); } } // Driver code int main() { char k[] = "geeks for geeks"; reverse(k); return 0; }
Java
// Java implementation of the approach import java.util.Arrays; import java.util.Stack; class GFG { // Function to reverse the words // of the given sentence static void reverse(String k) { // Create an empty character array stack Stack<String> s = new Stack<>(); String[] token = k.split(" "); // Push words into the stack for (int i = 0; i < token.length; i++) { s.push(token[i]); } while (!s.empty()) { // Get the words in reverse order System.out.print(s.peek() + " "); s.pop(); } } // Driver code public static void main(String[] args) { String k = "geeks for geeks"; reverse(k); } } // This code is contributed by Rajput-Ji
Python3
# Python3 implementation of the approach # Function to reverse the words # of the given sentence def reverse(k): # Create an empty character array stack s = [] token = k.split() # Push words into the stack for word in token : s.append(word); while (len(s)) : # Get the words in reverse order print(s.pop(), end = " "); # Driver code if __name__ == "__main__" : k = "geeks for geeks"; reverse(k); # This code is contributed by AnkitRai01
C#
// C# implementation of the approach using System; using System.Collections.Generic; class GFG { // Function to reverse the words // of the given sentence static void reverse(String k) { // Create an empty character array stack Stack<String> s = new Stack<String>(); String[] token = k.Split(' '); // Push words into the stack for (int i = 0; i < token.Length; i++) { s.Push(token[i]); } while (s.Count != 0) { // Get the words in reverse order Console.Write(s.Peek() + " "); s.Pop(); } } // Driver code public static void Main(String[] args) { String k = "geeks for geeks"; reverse(k); } } // This code is contributed by PrinciRaj1992
Javascript
<script> // JavaScript implementation of the approach // Function to reverse the words // of the given sentence function reverse(k) { // Create an empty character array stack let s = []; let token = k.split(" "); // Push words into the stack for (let i = 0; i < token.length; i++) { s.push(token[i]); } while (s.length > 0) { // Get the words in reverse order document.write(s[s.length - 1] + " "); s.pop(); } } // Driver code let k = "geeks for geeks"; reverse(k); </script>
geeks for geeks
Complejidad de tiempo: O(N)
Publicación traducida automáticamente
Artículo escrito por SnehaPasupula y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA