📌  相关文章
📜  反转给定字符串的单词 | 2套

📅  最后修改于: 2021-09-04 08:03:40             🧑  作者: Mango

给定字符串str ,任务是通过将字符串str 的每个单词视为一个单元来反转字符串。

例子:

In-place Reversal Approach:请参阅文章 Reverse words in a given 字符串以就地反转单词,然后反转整个字符串。
时间复杂度: O(N)
辅助空间: O(1)

基于堆栈的方法:在本文中,将讨论使用堆栈解决问题的方法。这里的想法是将str的所有单词压入Stack ,然后打印Stack的所有元素。请按照以下步骤解决问题:

  1. 创建一个Stack来存储字符串str 的每个单词。
  2. 迭代字符串str ,并用空格分隔符分隔str的每个单词。
  3. str 的所有单词压入堆栈。
  4. 将堆栈中的所有元素一一打印。

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to reverse the words
// of a given string
void printRev(string str)
{
    // Stack to store each
    // word of the string
    stack st;
 
    // Store the whole string
    // in string stream
    stringstream ss(str);
 
    string temp;
    while (getline(ss, temp, ' ')) {
 
        // Push each word of the
        // string into the stack
        st.push(temp);
    }
 
    // Print the string in reverse
    // order of the words
    while (!st.empty()) {
        cout << st.top() << " ";
        st.pop();
    }
}
 
// Driver Code
int main()
{
    string str;
    str = "geeks quiz practice code";
 
    printRev(str);
    return 0;
}


Java
// Java Program to implement
// the above approach
import java.util.*;
class GFG{
 
    // Function to reverse the words
    // of a given String
    static void printRev(String str)
    {
        // Stack to store each
        // word of the String
        Stack st = new Stack();
 
        // Store the whole String
        // in String stream
        String[] ss = str.split(" ");
 
        for (String temp : ss)
        {
 
            // Push each word of the
            // String into the stack
            st.add(temp);
        }
 
        // Print the String in reverse
        // order of the words
        while (!st.isEmpty())
        {
            System.out.print(st.peek() + " ");
            st.pop();
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String str;
        str = "geeks quiz practice code";
        printRev(str);
    }
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program to implement
# the above approach
 
# Function to reverse the words
# of a given string
def printRev(strr):
     
    # Stack to store each
    # word of the string
    strr = strr.split(" ")
    st = []
 
    # Store the whole string
    # in strream
    for i in strr:
 
        # Push each word of the
        # into the stack
        st.append(i)
 
    # Print the in reverse
    # order of the words
    while len(st) > 0:
        print(st[-1], end = " ")
        del st[-1]
 
# Driver Code
if __name__ == '__main__':
     
    strr = "geeks quiz practice code"
     
    printRev(strr)
 
# This code is contributed by mohit kumar 29


C#
// C# program to implement
// the above approach
using System;
using System.Collections;
 
class GFG{
 
// Function to reverse the words
// of a given String
static void printRev(string str)
{
     
    // Stack to store each
    // word of the String
    Stack st = new Stack();
 
    String[] sepearator = {" "};
     
    // Store the whole String
    // in String stream
    string[] ss = str.Split(sepearator,
                            int.MaxValue,
             StringSplitOptions.RemoveEmptyEntries);
 
    foreach(string temp in ss)
    {
 
        // Push each word of the
        // String into the stack
        st.Push(temp);
    }
 
    // Print the String in reverse
    // order of the words
    while (st.Count > 0)
    {
        Console.Write(st.Peek() + " ");
        st.Pop();
    }
}
 
// Driver Code
public static void Main(string[] args)
{
    string str;
    str = "geeks quiz practice code";
     
    printRev(str);
}
}
 
// This code is contributed by rutvik_56


Python3
# Python3 program to implement
# the above approach
 
# Function to reverse the words
# of a given strring
 
 
def printRev(string):
    # split by space and converting
    # string to list
    lis = list(string.split())
    # reverse the list
    lis.reverse()
    # printing the list
    print(*lis)
 
 
# Driver Code
if __name__ == '__main__':
 
    strr = "geeks quiz practice code"
 
    printRev(strr)
 
# This code is contributed by vikkycirus


Javascript


输出

code practice quiz geeks 

时间复杂度: O(N),其中 N 表示字符串的长度。
辅助空间: O(N)

方法#2:使用内置的Python函数

  • 因为句子中的所有单词都用空格分隔。
  • 我们必须使用split()将句子按空格分割。
  • 我们用空格分割所有单词并将它们存储在一个列表中。
  • 反转这个列表并打印出来。

蟒蛇3

# Python3 program to implement
# the above approach
 
# Function to reverse the words
# of a given strring
 
 
def printRev(string):
    # split by space and converting
    # string to list
    lis = list(string.split())
    # reverse the list
    lis.reverse()
    # printing the list
    print(*lis)
 
 
# Driver Code
if __name__ == '__main__':
 
    strr = "geeks quiz practice code"
 
    printRev(strr)
 
# This code is contributed by vikkycirus

Javascript


输出
code practice quiz geeks

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live