越到后面越不给力了,这题又看了答案。。
1 class Solution { 2 public: 3 vector<string> fullJustify(vector<string> &words, int L) { 4 vector<string> ans; 5 int cur = 0; 6 while (cur < words.size()) { 7 int len = 0; 8 int pre = cur; 9 while (cur < words.size()) { 10 int newlen = (len == 0? words[cur].size() : len + 1 + words[cur].size()); 11 if (newlen > L) break; 12 else len = newlen; 13 cur++; 14 } 15 int space = L - len; 16 int avgspace = 0; 17 if (cur != pre + 1 && cur != words.size()) { 18 avgspace = space / (cur - pre - 1); 19 space %= (cur - pre - 1); 20 } 21 string s; 22 for (int i = pre; i < cur; ++i) { 23 if (i == pre) s += words[i]; 24 else { 25 s += string(avgspace+1, ' '); 26 if (space && cur != words.size()) { 27 s += ' '; 28 space--; 29 } 30 s += words[i]; 31 } 32 } 33 s += string(space, ' '); 34 ans.push_back(s); 35 } 36 return ans; 37 } 38 };
C#
1 public class Solution { 2 public List<string> FullJustify(string[] words, int maxWidth) { 3 List<string> ans = new List<string>(); 4 int cur = 0; 5 while (cur < words.Length) { 6 int len = 0; 7 int pre = cur; 8 while (cur < words.Length) { 9 int newLen = (len == 0? words[cur].Length : len+1+words[cur].Length); 10 if (newLen > maxWidth) break; 11 else len = newLen; 12 cur++; 13 } 14 int space = maxWidth - len; 15 int avgSpace = 0; 16 if (cur != pre + 1 && cur != words.Length) { 17 avgSpace = space / (cur - pre - 1); 18 space %= (cur - pre - 1); 19 } 20 string s = ""; 21 for (int i = pre; i < cur; i++) { 22 if (i == pre) s += words[i]; 23 else { 24 s += new string(' ', avgSpace+1); 25 if (space != 0 && cur != words.Length) { 26 s += ' '; 27 space--; 28 } 29 s += words[i]; 30 } 31 } 32 s += new string(' ', space); 33 ans.Add(s); 34 } 35 return ans; 36 } 37 }