C# Solution With Stack


  • 0
    P
    public class Solution {
        public string ReverseWords(string s) {
            // Stack to reverse words
            var stack = new Stack<char>();
            // Buffer to store our work in progress
            var copyOfS = new StringBuilder();
            // Loop thru character
            foreach(var c in s) {
                // Space character is a trigger to empty stack
                if (c == ' ') {
                    // Pop characters from the stack
                    while (stack.Count != 0) {
                        copyOfS.Append(stack.Pop());
                    }
                    // Put space character into the string
                    copyOfS.Append(c);
                    // Move to the next word
                    continue;
                }
                // Push yet another character into stack
                stack.Push(c);
            }
            // Work on the remaining part in the stack
            while (stack.Count != 0) {
                copyOfS.Append(stack.Pop());
            }
            // Hand-off reverted copy of the string back to the client
            return copyOfS.ToString();
        }
    }
    

Log in to reply
 

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