my c# solution, 100% beating


  • 0
    I
        public void ReverseWords(char[] s) {
            if(s == null || s.Length <= 0)
            {
                return;
            }
            
            int l = s.Length -1;
            int i = 0;
            
            Swap(s, 0, l);
            
            // now swap individual words
            i =1;
            int stIndex = 0;
            
            for (; i < s.Length;i++)
            {
                if(s[i] != ' ')
                {
                    // no op
                }
                else
                {
                    // end of word encountered
                    Swap (s, stIndex, i-1);
                    
                    // new StartIndex 
                    stIndex = i+1;
                }
            }
            Swap(s, stIndex, i-1);
        }
        
        private void Swap(char [] s, int stIndex, int endIndex)
        {
            char temp = ' ';
            
            while(stIndex < endIndex)
            {
                temp = s[endIndex];
                s[endIndex] = s[stIndex];
                s[stIndex] = temp;
                
                stIndex++;
                endIndex--;
            }
        }
    }

Log in to reply
 

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