# 反向字符串中的單詞

## 問題陳述

”表示您將得到一個大小為n的字符串s。 以相反的順序打印字符串，以使最後一個單詞成為第一個單詞，第二個單詞成為第二個單詞，依此類推。 在此，字符串是指包含單詞而不是由字符組成的單詞的句子。

## 例

`s = "TutorialCup makes learning easy"`
`easy learning makes TutorialCup`

begin = 12，res =“簡單易學”

res =“簡單易學使TutorialCup”

`s = "Contributed by Akshita Jain"`
`Jain Akshita by Contributed`

## 字符串問題中反詞的算法

```1. Initialize a string s of size n.
2. Create a function to reverse the words of the given string which accepts a string variable as it's a parameter.
3. After that, create two variables of integer type begin and end. Initialize the variable end as the size of the string.
4. Create an empty string variable to store the result.
5. Traverse through the string from the last character to first and check if the character at current index in the given string is a white space, update the variable begin as current index + 1 and while variable begin is not equal to the variable end, add the character at index begin + 1 of the given string in the result string variable.
6. Add a white space in the result string variable and update the variable end as the current index.
7. Update variable begin as 0.
8. Traverse again, while variable begin is not equal to variable end, add the character at index begin + 1 of the given string in the result string variable.
9. Return the resulting string variable.```

## 推薦碼

### C ++程序反轉字符串中的單詞

```#include<bits/stdc++.h>
using namespace std;

string reverseStringWords(string s){
int i = s.length() - 1, begin, end = i + 1;
string res = "";

while(i >= 0){
if(s[i] == ' '){
begin = i + 1;
while(begin != end)
res += s[begin++];

res += ' ';
end = i;
}

i--;
}
begin = 0;
while(begin != end)
res += s[begin++];

return res;
}

int main(){
string s = "TutorialCup makes learning easy";
cout << reverseStringWords(s);

return 0;
}
```
`easy learning makes TutorialCup`

### Java程序反轉字符串中的單詞

```import java.io.*;
import java.util.*;
import java.lang.*;

class reverse{
static String reverseStringWords(String s){
int i = s.length() - 1;
int begin, end = i + 1;
String res = "";

while(i >= 0){
if(s.charAt(i) == ' '){
begin = i + 1;
while(begin != end)
res += s.charAt(begin++);

res += ' ';

end = i;
}
i--;
}

begin = 0;
while(begin != end)
res += s.charAt(begin++);

return res;
}

public static void main(String[] args){
String s = "TutorialCup makes learning easy";

System.out.print(reverseStringWords(s));
}
}
```
`easy learning makes TutorialCup`

## 複雜度分析

### 時間複雜度

O（N） 其中n是給定字符串中的字符總數。

### 空間複雜度

O（N） 因為我們使用空間來存儲n個元素。