My C# solution


  • 0
    S
    public class Solution {
        public IList<string> FullJustify(string[] words, int maxWidth) 
        {
            var result = new List<string>();
            for(int i=0, w; i<words.Count(); i = w)
            {
                var length = -1;
                var sb = new StringBuilder(words[i]);
                for(w = i; w<words.Count() && length + words[w].Length+1<=maxWidth; w++)
                {
                    length+=words[w].Length+1;
                }
                if(w==i+1)
                {
                   sb.Append(' ', maxWidth-words[w-1].Length);
                }
                else if(w==words.Count())
                {
                    for(int j =i+1; j<w; j++)
                    {
                        sb.Append(" ");
                        sb.Append(words[j]);
                    }
                    sb.Append(' ', maxWidth-length);
                }
                else
                {
                    var space = (maxWidth-length)/(w-i-1)+1;
                    var extra = (maxWidth-length)%(w-i-1);
                    for(int j =i+1; j<w; j++)
                    {
                        sb.Append(' ', space);
                        if(extra-- > 0)
                            sb.Append(" ");
                        sb.Append(words[j]);
                    }
                }
                result.Add(sb.ToString());
            }
            return result;
        }
    }
    

Log in to reply
 

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