使用堆栈反转字符串的单词
给定由多个单词组成的字符串str ,任务是逐字反转整个字符串。
例子:
Input: str = “I Love To Code”
Output: Code To Love I
Input: str = “data structures and algorithms”
Output: algorithms and structures data
方法:这个问题不仅可以在 strtok() 的帮助下解决,还可以通过使用 STL C++ 中的堆栈容器类来解决,具体步骤如下:
- 创建一个空堆栈。
- 遍历整个字符串,同时将字符串的字符添加到临时
变量,直到你得到一个空格('')并将该临时变量推入堆栈。 - 重复上述步骤,直到字符串结束。
- 从堆栈中弹出单词,直到堆栈不为空,这将是相反的顺序。
下面是上述方法的实现:
C++
//C++ implementation of the above approach
#include
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 stc;
//create an empty temporary string
string temp="";
//traversing the entire string
for(int i=0;i
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 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
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to reverse the words
// of the given sentence
void reverse(char k[])
{
// Create an empty character array stack
stack 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 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 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.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
输出:
Code To Love I
时间复杂度: O(N)
另一种方法:这里讨论了一种不使用堆栈的方法。这个问题也可以通过以下步骤使用堆栈来解决:
- 创建一个空堆栈。
- 在 strtok() 的帮助下,使用空格作为分隔符将输入字符串标记为单词
- 将单词压入堆栈。
- 从堆栈中弹出单词,直到堆栈不为空,这将是相反的顺序。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to reverse the words
// of the given sentence
void reverse(char k[])
{
// Create an empty character array stack
stack 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 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 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.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
输出:
geeks for geeks
时间复杂度: O(N)