版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址
http://blog.csdn.net/lzuacm。
Leetcode 557. 反转字符串中的单词 III - 题解
Leetcode 557. Reverse Words in a String III
在线提交: https://leetcode.com/problems/reverse-words-in-a-string-iii/description/
题目描述
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例 1:
输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc"
注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
思路:
滤除原字符串中的空格,
已AC代码:
public class Solution
{
public string ReverseWords(string s)
{
StringBuilder sb = new StringBuilder();
s = s.Trim();
var words = s.Split(' ');
foreach (var word in words)
{
for (int i = word.Length - 1; i >= 0; i--)
{
sb.Append(word[i]);
}
sb.Append(" ");
}
return sb.ToString().Trim();
}
}
Rank:
You are here!
Your runtime beats 97.76%
of csharp submissions.