Guest User

Untitled

a guest
Oct 23rd, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. public class TextJustification {
  2.  
  3. public String find(String [] words, int maxWidth, int index){
  4. if(index<words.length){
  5. String result = "";
  6. int currentLen = 0;
  7. int remainLength = maxWidth;
  8. while(result.length()<maxWidth && index<words.length){
  9. if(remainLength>=words[index].length()+1){ //remainingLength+1 for space
  10. if(!result.equals("")){
  11. result += "@" + words[index];
  12. currentLen = words[index].length()+1;
  13. }else{
  14. result += words[index];
  15. currentLen = words[index].length();
  16. }
  17. remainLength -= currentLen;
  18. index++;
  19. }else if(remainLength>0){
  20. if(result.contains("@")==false){
  21. for (int i = 0; i < remainLength; i++) {
  22. result = result + " ";
  23. }
  24. }else {
  25. //go in only if there at least 2 words
  26. String[] arr = result.split("@");
  27. int mod = (remainLength % (arr.length - 1));
  28. int splitedSpace = remainLength / (arr.length - 1);
  29. String spaces = " ";
  30. for (int i = 0; i < splitedSpace; i++) {
  31. spaces = spaces + " ";
  32. }
  33. String leftmost = spaces;
  34. for (int i = 0; i < mod; i++) {
  35. leftmost = leftmost + " ";
  36. }
  37. result = result.replaceFirst("@", leftmost);
  38. result = result.replaceAll("@", spaces);
  39. }
  40. }
  41. }
  42. result = result.replaceAll("@", " ");
  43. return result + "\n" + find(words,maxWidth,index);
  44. }else{
  45. return "";
  46. }
  47. }
  48.  
  49. public static void main(String[] args) {
  50. TextJustification t = new TextJustification();
  51. String [] words = {"This", "is", "a", "text", "justification","problem","in","tutorial","horizon"};
  52. int maxWidth = 25;
  53. System.out.println(t.find(words,maxWidth,0));
  54. }
  55. }
Add Comment
Please, Sign In to add comment