C# O(n) simple function 15 lines of code


  • 0
    Z
    public class Solution {
        public string ReverseWords(string s) {
            int count = 0;
            StringBuilder sb = new StringBuilder(s);
            for (int i = sb.Length-1; i >= 0; i--) {
                count++;
                if(sb[i] == ' ' || i == 0) {
                    int k = i+count-1;
                    for(int j = i == 0 ? 0: i+1; j < k; j++) {
                        char temp = sb[k];
                        sb[k] = sb[j];
                        sb[j] = temp;
                        k--;
                    }
                    count = 0;
                }
            }
            return sb.ToString();
        }
    }
    
    

Log in to reply
 

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