C#LeetCode刷题之#557-反转字符串中的单词 III(Reverse Words in a String III)

C#LeetCode刷题之#557-反转字符串中的单词 III(Reverse Words in a String III)

问题

给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

输入: “Let’s take LeetCode contest”

输出: “s’teL ekat edoCteeL tsetnoc” 

注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。

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.

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.

示例

public class Program {

    public static void Main(string[] args) {
        var s = "s'teL ekat edoCteeL tsetnoc";

        var res = ReverseWords(s);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static string ReverseWords(string s) {
        var words = s.Split(' ');
        var res = new StringBuilder();
        foreach(var word in words) {
            res.Append(word.Reverse().ToArray());
            res.Append(' ');
        }
        return res.ToString().Trim();
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

Let's take LeetCode contest

分析:

显而易见,以上算法的时间复杂度为: O(n)

本文由 .Net中文网 原创发布,欢迎大家踊跃转载。

转载请注明本文地址:https://www.byteflying.com/archives/3955

(1)
上一篇 2020年06月08日 20:54
下一篇 2020年06月08日 20:58

相关推荐

发表回复

登录后才能评论