📜  反转单个单词

📅  最后修改于: 2022-05-13 01:57:06.686000             🧑  作者: Mango

反转单个单词

给定一个字符串str,我们需要打印单个单词的反转。
例子:

Input : Hello World
Output : olleH dlroW
 
Input :  Geeks for Geeks
Output : skeeG rof skeeG

方法1(简单):生成所有用空格分隔的单词。一个一个地反转单词并打印它们,用空格分隔。
方法 2(空间高效):我们使用堆栈将所有单词压入空格之前。一旦遇到空格,我们就清空堆栈。

C++
// C++ program to reverse individual words in a given
// string using STL list
#include 
using namespace std;
 
// reverses individual words of a string
void reverseWords(string str)
{
    stack 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 st=new Stack();
  
    // 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 reverserWords(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"
    reverserWords(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 st = new Stack();
 
    // 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


CPP
#include
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<


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);
 
    }
 
}


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


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 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

Python|反转句子中的每个单词
在 C++ 中使用字符串流

CPP

#include
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<

输出:

skeeGrofskeeG si doog ot nrael 

时间复杂度:O(n)
空间复杂度:O(n)
使用Java 8 流

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

替代方法:使用 StringBuffer 类打印反转的字符串。

脚步:

  1. 首先,将字符串对象转换为 StringBuffer 对象。
  2. 通过使用 StringBuffer 类的 reverse 方法反转字符串。
  3. 现在,将反向序列存储到字符串数组中。
  4. 运行一个循环,使用这些反向词创建一个新字符串
  5. 最后,返回新字符串。

执行:

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

替代方法:存储反转的字符串而不仅仅是打印

脚步:

  1. 创建一个堆栈并压入给定输入字符串的所有字符。
  2. 创建“rev”和“temp”字符串
  3. 执行以下步骤,直到堆栈变空。
  4. 如果堆栈的 peek( ) 是一个字符,则将其附加到 temp
  5. 如果堆栈的 peek( ) 是空格,则将空格附加到 rev 并将 temp 附加到 rev
  6. 最后,如果 temp 不为空,则将 temp 附加到 rev 前面
  7. 返回反转的字符串

执行:

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 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

时间复杂度: O(n)。