---
tags: LeetCode
---
# 557. Reverse Words in a String III
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
```
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
```
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
輸入範本如下
```C#
public class Solution {
public string ReverseWords(string s) {
}
}
```
#### 自我限制
不准使用 Join , Spilt , Reverse , Aggregat 等方法
```C#
116 ms 34.9 MB
You are here!
Your runtime beats 36.87 % of csharp submissions.
public string ReverseWords(string s)
{
return string.Join(" ", s.Trim().Split(' ').Select(word => new string(word.Reverse().ToArray())));
}
```
```C#
116 ms 34.9 MB
You are here!
Your runtime beats 36.87 % of csharp submissions.
public string ReverseWords(string s)
{
var build = s.Split(' ').Select(word => new string(word.Reverse().ToArray())).Aggregate(new StringBuilder(), (builder, word) => builder.Append(word + " "));
return build.ToString().Trim();
}
```
### 直覺想法
字與字之間是使用空白字元去間隔的 , 因此只要發現空白字元的時候 , 就去反轉之前發現的字元
儲存媒介使用 StringBuilder or char[] , 效果差不多.
```C#
84 ms 31.1 MB
You are here!
Your runtime beats 97.64 % of csharp submissions.
public string ReverseWords(string s)
{
StringBuilder stringBuilder = new StringBuilder(s);
for (int left = 0, right = 0; right < s.Length; left = ++right)
{
while (right < s.Length && s[right] != ' ')
{
right++;
}
Swap(stringBuilder, left, right - 1);
}
return stringBuilder.ToString().Trim();
void Swap(StringBuilder builder, int l, int r)
{
for (; l < r; l++, r--)
{
char temp = builder[l];
builder[l] = builder[r];
builder[r] = temp;
}
}
}
```
```C#
84 ms 31 MB
You are here!
Your runtime beats 97.64 % of csharp submissions.
public string ReverseWords(string s)
{
var cArr = s.ToCharArray();
for (int left = 0, right = 0; right < cArr.Length; left = ++right)
{
while (right < cArr.Length && cArr[right] != ' ')
{
right++;
}
Swap(cArr, left, right - 1);
}
return new string(cArr).Trim();
void Swap(char[] arr, int l, int r)
{
for (; l < r; l++, r--)
{
char temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
}
}
}
```
### Thank you!
You can find me on
- [GitHub](https://github.com/s0920832252)
- [Facebook](https://www.facebook.com/fourtune.chen)
若有謬誤 , 煩請告知 , 新手發帖請多包涵
# :100: :muscle: :tada: :sheep: