Starting to play LeetCode today - question 151

Starting with question 151:

https://leetcode.com/problems/reverse-words-in-a-string/description/

Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
My answer:

using System;
using System.Text;
public class Solution {
    public string ReverseWords(String s) {

    String s2=reverseString(s);
    var chars2=s2.ToCharArray();

        var words=s2.Split(null);

    StringBuilder wordBuffer=new StringBuilder();
        foreach(String word in words)
        {
             if(!String.IsNullOrEmpty(word))
             {
                  wordBuffer.Append(reverseString(word));  
                  wordBuffer.Append(" ");
             }

        }
        return wordBuffer.ToString().Trim();
    }

    private String reverseString(String original)
    {
        var chars=original.ToCharArray();
StringBuilder builder=new StringBuilder();
for (int i=chars.Length; i>0; i--)
{
builder.Append(chars[i-1]);
}
        return builder.ToString();
    }
}

Comments

Popular posts from this blog

Completed the LeetCode #2 adding two numbers