Dada una string str, necesitamos imprimir el reverso de las palabras individuales.
Ejemplos:
Input : Hello World Output : olleH dlroW Input : Geeks for Geeks Output : skeeG rof skeeG
Método 1 (Simple): Genere todas las palabras separadas por espacios. Invierta las palabras una a una e imprímalas separadas por espacios.
Método 2 (espacio eficiente): usamos una pila para empujar todas las palabras antes del espacio. Tan pronto como encontramos un espacio, vaciamos la pila.
Implementación:
C++
// C++ program to reverse individual words in a given // string using STL list #include <bits/stdc++.h> using namespace std; // reverses individual words of a string void reverseWords(string str) { stack<char> st; // Traverse given string and push all characters // to stack until we see a space. for (int i = 0; i < str.length(); ++i) { if (str[i] != ' ') st.push(str[i]); // When we see a space, we print contents // of stack. else { while (st.empty() == false) { cout << st.top(); st.pop(); } cout << " "; } } // Since there may not be space after // last word. while (st.empty() == false) { cout << st.top(); st.pop(); } } // Driver program to test function int main() { string str = "Geeks for Geeks"; reverseWords(str); return 0; }
Java
// Java program to reverse individual // words in a given string using STL list import java.io.*; import java.util.*; class GFG { // reverses individual words of a string static void reverseWords(String str) { Stack<Character> st=new Stack<Character>(); // Traverse given string and push all // characters to stack until we see a space. for (int i = 0; i < str.length(); ++i) { if (str.charAt(i) != ' ') st.push(str.charAt(i)); // When we see a space, we print // contents of stack. else { while (st.empty() == false) { System.out.print(st.pop()); } System.out.print(" "); } } // Since there may not be space after // last word. while (st.empty() == false) { System.out.print(st.pop()); } } // Driver program to test above function public static void main(String[] args) { String str = "Geeks for Geeks"; reverseWords(str); } }
Python3
# Python3 program to reverse individual words # in a given string using STL list # reverses individual words of a string def reverseWords(string): st = list() # Traverse given string and push all characters # to stack until we see a space. for i in range(len(string)): if string[i] != " ": st.append(string[i]) # When we see a space, we print # contents of stack. else: while len(st) > 0: print(st[-1], end= "") st.pop() print(end = " ") # Since there may not be space after # last word. while len(st) > 0: print(st[-1], end = "") st.pop() # Driver Code if __name__ == "__main__": string = "Geeks for Geeks" reverseWords(string) # This code is contributed by # sanjeev2552
C#
// C# program to reverse individual // words in a given string using STL list using System; using System.Collections.Generic; class GFG { // reverses individual words // of a string public static void reverseWords(string str) { Stack<char> st = new Stack<char>(); // Traverse given string and push // all characters to stack until // we see a space. for (int i = 0; i < str.Length; ++i) { if (str[i] != ' ') { st.Push(str[i]); } // When we see a space, we // print contents of stack. else { while (st.Count > 0) { Console.Write(st.Pop()); } Console.Write(" "); } } // Since there may not be // space after last word. while (st.Count > 0) { Console.Write(st.Pop()); } } // Driver Code public static void Main(string[] args) { string str = "Geeks for Geeks"; reverseWords(str); } } // This code is contributed // by Shrikant13
skeeG rof skeeG
python | Invierta cada palabra en una oración
usando stringstream en C++ :
Implementación:
CPP
#include<bits/stdc++.h> using namespace std; void printWords(string str) { // word variable to store word string word; // making a string stream stringstream iss(str); // Read and print each word. while (iss >> word){ reverse(word.begin(),word.end()); cout<<word<<" "; } } // Driver code int main() { string s = "GeeksforGeeks is good to learn"; printWords(s); return 0; } // This code is contributed by Nikhil Rawat
skeeGrofskeeG si doog ot nrael
Complejidad temporal : O(n)
Complejidad espacial : O(n)
Uso de flujos de Java 8
Implementación:
Java
import java.util.Arrays; import java.util.stream.Collectors; // This code is contributed by Mayank Sharma public class reverseIndividual { public static void main(String[] args) { String str = "Welcome to GFG"; // Splitting the string based on space and reverse each part // and then join String result = Arrays.asList(str.split(" ")) .stream() .map(s -> new StringBuilder(s).reverse()) .collect(Collectors.joining(" ")); System.out.println(result); } }
emocleW ot GFG
Enfoque alternativo: para imprimir la string invertida utilizando la clase StringBuffer.
Pasos:
- Primero, convierta el objeto de string en un objeto StringBuffer.
- Usando el método inverso de la clase StringBuffer, invierta la string.
- Ahora, almacene la secuencia inversa en una array de strings.
- Ejecute un ciclo que creará una nueva string usando estas palabras inversas
- Finalmente, devuelve la nueva string.
Implementación:
Java
/*package whatever //do not write package name here */ import java.io.*; class GFG { static String makeReverse(String str) { StringBuffer s = new StringBuffer(str); str = s.reverse().toString(); String [] rev = str.split(" "); StringBuffer reverse = new StringBuffer(); for(int i = rev.length - 1; i >= 0; i--) { reverse.append(rev[i]).append(" "); } return reverse.toString(); } public static void main (String[] args) { String str = "Geeks for Geeks"; System.out.println(makeReverse(str)); } } // This code is contributed by Adarsh Kumar
skeeG rof skeeG
Enfoque alternativo: para almacenar la string invertida en lugar de simplemente imprimir
Pasos:
- Cree una pila y empuje todos los caracteres de la string de entrada dada.
- Crear strings ‘rev’ y ‘temp’
- Realice los siguientes pasos hasta que la pila se vacíe.
- Si el vistazo() de la pila es un carácter, agréguelo a temp
- Si el vistazo ( ) de la pila es un espacio, agregue espacio a rev y también temp a rev
- Finalmente, si la temperatura no está vacía, agregue la temperatura a revoluciones en el frente
- Devuelve la string invertida
Implementación:
Java
//java program to reverse the individual words import java.util.Stack; public class Reverse { //function to reverse the individual words String reverse(String str) { //create a stack to access the string from end Stack<Character> s = new Stack<>(); //push all the characters of the stack for(int i = 0; i < str.length();i++) s.push(str.charAt(i)); //rev string to store the required output String rev = ""; String temp = ""; //till the stack becomes empty while(!s.isEmpty()) { //if top of the stack is a letter, //then append it to temp; if(Character.isLetter(s.peek())) temp = temp + s.pop(); //if it is a space, the append space to rev //and also temp to rev else { rev = " " + temp +rev; //make the temp empty temp = ""; s.pop(); } } //if temp is not empty, add temp to rev at the front if(temp != "") rev = temp + rev; //return the output string return rev; } public static void main(String[] args) { String str = "Geeks for Geeks"; Reverse obj = new Reverse(); System.out.println(obj.reverse(str)); } } //This method is contributed by Likhita AVL
skeeG rof skeeG
Complejidad temporal: O(n).
Usando Split e iterador en Python
Implementación:
Python3
def rev_sentence(sentence): # first split the string into words words = sentence.split(' ') reverse_sentence="" for i in words: reverse_sentence+=i[::-1]+' ' # then reverse the split string list and join using space # finally return the joined string return reverse_sentence if __name__ == "__main__": input = 'geeks quiz practice code' print (rev_sentence(input))
skeeg ziuq ecitcarp edoc
Complejidad de tiempo: O(n)
Método: Uso de funciones de unir y dividir
Implementación:
Python3
# Python code to reverse words s = " Geeks for Geeks" l = [] # splitting the string s = s.split() for i in s: # reversing each word l.append(i[::-1]) # printing string using join # function after reversing the # words print(" ".join(l))
skeeG rof skeeG
Publicación traducida automáticamente
Artículo escrito por AFZAL ANSARI y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA