A 1-Line C# Solution and some other alternative ways


  • 1
    L
    //1. Using Array.Reverse() and String.Join() to Connect strings
    using System.Text.RegularExpressions;
    public string ReverseWords(string s) {
        return String.Join(" ", new Regex(" +").Split(s).Reverse()).Trim();
    }
    
    //2. All Chars operations
    public string ReverseWord(string s) {
        StringBuilder sb = new StringBuilder();
        for(int i = s.Length - 1, j = i; i >= 0; j = i)
            if(s[i] != ' '){
                while(j - 1 >= 0 && s[j - 1] != ' ') j--;
                for(int k = j; k <= i; k++) sb.Append(s[k]);
                sb.Append(" ");
                i = j - 1;
            }else i--;
        return sb.ToString().Trim();
    }
    
    //3. Using Regular Expression to split strings and loop it
    public string ReverseWords(string s) {
        string[] quick = new Regex(" +").Split(s);
        StringBuilder sb = new StringBuilder();
        for(int i = quick.Length - 1; i >= 0; i--)
            sb.Append(quick[i].Trim() + " ");
        return sb.ToString().Trim();
    }
    
    //4. Using string.split to split strings and loop it
    public string ReverseWords(string s) {
        string[] quick = s.Trim().Split(' ');
        StringBuilder sb = new StringBuilder();
        for(int i = quick.Length - 1; i >= 0; i--)
            if(quick[i].Trim().Length > 0) sb.Append(quick[i].Trim() + " ");
        return sb.ToString().Trim();
    }

  • 0
    L
    // A Recursive way got Output Limit Exceeded error
    public string ReverseWords(string s) {
        if(s.Trim().Length == 0) return string.Empty;
        int index1 = 0;
        while(s[index1] == ' ') index1++;
        int index2 = index1;
        while(index2 + 1 < s.Length && s[index2 + 1] != ' ') index2++;
        return ReverseWords(s.Substring(index2 + 1) + " " + s.Substring(index1, index2 - index1 + 1)).Trim();
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.