1. 程式人生 > >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) 。