c# solution


  • 0
    N
    public class Solution {
        public string ReverseWords(string s)
        {
            var start = 0;
            var end = 0;
            var sb = new StringBuilder(s);
            for (var i = 0; i < s.Length; i++)
            {
                if (i - 1 >= 0 && s[i] != ' ' && s[i - 1] == ' ')
                {
                    start = i;
                }
                if (s[i] != ' ' && (i == s.Length - 1 || (i + 1 < s.Length && s[i + 1] == ' ')))
                {
                    end = i;
                    reverse(sb, start, end);
                }
    
            }
    
            return sb.ToString();
        }
        
        public void reverse(StringBuilder sb, int start, int end){
            while(start<=end){
                var t = sb[start];
                sb[start] = sb[end];
                sb[end] = t;
                start++;
                end--;
            }
        }
    }
    

Log in to reply
 

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