Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. class Solution {
  2. public:
  3. vector<string> fullJustify(vector<string>& words, int max_width) {
  4. vector<string> result;
  5. int start_indx = 0, end_indx = 0, input_len = words.size();
  6.  
  7. while (start_indx < input_len) {
  8. int tl_char = 0, tl_words = 0;
  9.  
  10. while (end_indx < input_len &&
  11. (tl_char + words[end_indx].size() + tl_words <= max_width) ) {
  12. tl_char += words[end_indx].size();
  13. tl_words += 1;
  14. end_indx++;
  15. }
  16.  
  17. string tmp_rslt;
  18. int tl_space_avail = max_width - tl_char;
  19.  
  20. for (int i=start_indx; i < end_indx; i++) {
  21. tmp_rslt.append(words[i]);
  22. tl_words--;
  23.  
  24. if (tl_space_avail && tl_words) {
  25. int num_spaces = 0;
  26.  
  27. //if your are on the last line, num spaces is 1
  28. if (end_indx == input_len) {
  29. num_spaces = 1;
  30. } else {
  31. //calculate space for every word, tl_words is already 1 less;
  32. num_spaces = (tl_space_avail % tl_words) ?
  33. (tl_space_avail / tl_words) + 1 :
  34. (tl_space_avail / tl_words);
  35.  
  36. }
  37.  
  38. tmp_rslt.append(num_spaces, ' ');
  39. tl_space_avail -= num_spaces;
  40. }
  41. }
  42.  
  43. //for last line or if a line has only 1 word , then tl_words = 0
  44. //append all the remaining spaces
  45. if (tl_space_avail) {
  46. tmp_rslt.append(tl_space_avail, ' ');
  47. }
  48.  
  49. result.push_back(tmp_rslt);
  50. start_indx = end_indx;
  51. }
  52. return result;
  53. }
  54. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement