A C# solution using two pointers and char array


  • 0
    J
    public class Solution {
    public string ReverseWords(string s) {
        if(s==null || s.Length==0) { return s; }
        int n=s.Length; char[] chars=new char[n]; int i=n-1; int index=0;
        for(int k=0; k<=n-1; k++) { chars[k]='\0'; }
        while(i>=0)
        {
            while(i>=0 && s[i]==' ') { i--; }
            if(i>=0)
            {
                if(index!=0) { chars[index++]=' '; }
                int j=i;
                while(j>=0 && s[j]!=' ') { j--; }
                for(int k=j+1; k<=i; k++)
                { chars[index++]=s[k]; }
                i=j;
            }
        }
        
        string r = new String(chars, 0, index);
        return r;
    } }

Log in to reply
 

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