C#版(击败100.00%的提交) - Leetcode 151. 翻转字符串里的单词 - 题解

版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址
http://blog.csdn.net/lzuacm

C#版 - Leetcode 151. 翻转字符串里的单词 - 题解

151.Reverse Words in a String
在线提交: https://leetcode-cn.com/problems/reverse-words-in-a-string/

题目描述


给定一个字符串,逐个翻转字符串中的每个单词。

示例:

输入: "the sky is blue",
输出: "blue is sky the".

说明:

  • 无空格字符构成一个单词。
  • 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
  • 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

进阶: 请选用C语言的用户尝试使用 O(1) 时间复杂度的原地解法。


  ●  题目难度: Medium

思路:
记得将连续的空格替换为一个,使用Split(new char[] {’ ‘,’\t’}, StringSplitOptions.RemoveEmptyEntries);

已AC代码:

public class Solution
{
    public string ReverseWords(string s)
    {
        StringBuilder sb = new StringBuilder();
        s = s.Trim();
        var words = s.Split(new char[] {' ','\t'}, StringSplitOptions.RemoveEmptyEntries);
        for (int i = words.Length; i > 0; i--)
        {
            foreach (var ch in words[i-1])
            {
                sb.Append(ch);
            }
            sb.Append(" ");
        }
        return sb.ToString().Trim();
    }
}

Rank:

You are here! Your runtime beats <kbd>100.00%</kbd> of csharp submissions.

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务