Skip to content

Commit 76a8508

Browse files
author
Longerhaha
authored
Merge pull request gzc426#16 from Longerhaha/Longerhaha-patch-4
添加题解至乔戈里leetcode每日一题库
2 parents 8d2c0c9 + 0916fc0 commit 76a8508

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
## 557_(反转字符串中的单词 III)Reverse Words in a String III
2+
## 1 问题描述、输入输出与样例
3+
### 1.1 问题描述
4+
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。<br>
5+
__注意__:<br>
6+
在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
7+
### 1.2 输入与输出
8+
输入:
9+
* string s:输入的字符串s
10+
11+
输出:
12+
* string:反转字符串后的字符串
13+
### 1.3 样例
14+
#### 1.3.1 样例1
15+
输入: "Let's take LeetCode contest"<br>
16+
输出: "s'teL ekat edoCteeL tsetnoc"
17+
## 2 思路描述与代码
18+
### 2.1 思路描述(单词反转法)
19+
start 记录字符串中每个单词的起始位置
20+
```cpp
21+
for( c in String s which is s[i]){
22+
if(c == ' '){
23+
reverse s.substr(start, i);
24+
start = i + 1;
25+
}
26+
}
27+
```
28+
### 2.2 代码
29+
```cpp
30+
string reverseWords(string s) {
31+
s += ' ';
32+
int len = s.size();
33+
int start = 0;
34+
for( int i = 0; i < len; i++ ){
35+
if(s[i] == ' '){
36+
reverse(s.begin() + start, s.begin() + i);
37+
start = i + 1;
38+
}
39+
}
40+
s.pop_back();
41+
return s;
42+
}
43+
```
44+
## 3 思考与拓展
45+
### 3.1 思考
46+
#### 3.1.1 其他方法
47+
无。
48+
#### 3.1.2 复杂度分析
49+
方法|空间复杂度|时间复杂度
50+
--- | --- | ---
51+
单词反转法|O(1)|O(n)
52+
#### 3.1.3 难点分析
53+
1. 如何记录起始位置
54+
2. 如何处理字符串的最后一个单词
55+
### 3.2 拓展
56+
如果给你的是链表数据或者数组数据呢?

0 commit comments

Comments
 (0)