Reverse the words in a string but maintain the separator positions


  • 0
    P

    Hello, Hi There! should be There, Hi Hello!


  • 0

    Any space requirement?


  • 0
    S

    this code reverse each word, include punctuation, but keep positions.

    var stack = new Stack<char>();
            for (var i = 0; i < s.Length; i++)
            {
                if (s[i] != ' ')
                {
                    stack.Push(s[i]);
                    continue;
                }
    
                while (stack.Count > 0)
                {
                    s[i - stack.Count] = stack.Pop();
                }
            }

Log in to reply
 

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