|
62 | 62 | */
|
63 | 63 | public class _418 {
|
64 | 64 |
|
65 |
| - /**credit: https://discuss.leetcode.com/topic/62455/21ms-18-lines-java-solution |
66 |
| - * |
67 |
| - 1. String s = String.join(" ", sentence) + " " ;. This line gives us a formatted sentence to be put to our screen. |
68 |
| - 2. start is the counter for how many valid characters from s have been put to our screen. |
69 |
| - 3. if (s.charAt(start % l) == ' ') is the situation that we don't need an extra space for current row. The current row could be successfully fitted. So that we need to increase our counter by using start++. |
70 |
| - 4. The else is the situation, which the next word can't fit to current row. So that we need to remove extra characters from next word. |
71 |
| - 5. start / s.length() is (# of valid characters) / our formatted sentence. |
72 |
| - */ |
73 |
| - public int wordsTyping(String[] sentence, int rows, int cols) { |
74 |
| - String s = String.join(" ", sentence) + " "; |
75 |
| - int start = 0; |
76 |
| - int l = s.length(); |
77 |
| - for (int i = 0; i < rows; i++) { |
78 |
| - start += cols; |
79 |
| - if (s.charAt(start % l) == ' ') { |
80 |
| - start++; |
81 |
| - } else { |
82 |
| - while (start > 0 && s.charAt((start - 1) % l) != ' ') { |
83 |
| - start--; |
| 65 | + public static class Solution1 { |
| 66 | + /** |
| 67 | + * credit: https://discuss.leetcode.com/topic/62455/21ms-18-lines-java-solution |
| 68 | + * <p> |
| 69 | + * 1. String s = String.join(" ", sentence) + " " ;. This line gives us a formatted sentence to be put to our screen. |
| 70 | + * 2. start is the counter for how many valid characters from s have been put to our screen. |
| 71 | + * 3. if (s.charAt(start % l) == ' ') is the situation that we don't need an extra space for current row. The current row could be successfully fitted. So that we need to increase our counter by using start++. |
| 72 | + * 4. The else is the situation, which the next word can't fit to current row. So that we need to remove extra characters from next word. |
| 73 | + * 5. start / s.length() is (# of valid characters) / our formatted sentence. |
| 74 | + */ |
| 75 | + public int wordsTyping(String[] sentence, int rows, int cols) { |
| 76 | + String s = String.join(" ", sentence) + " "; |
| 77 | + int start = 0; |
| 78 | + int l = s.length(); |
| 79 | + for (int i = 0; i < rows; i++) { |
| 80 | + start += cols; |
| 81 | + if (s.charAt(start % l) == ' ') { |
| 82 | + start++; |
| 83 | + } else { |
| 84 | + while (start > 0 && s.charAt((start - 1) % l) != ' ') { |
| 85 | + start--; |
| 86 | + } |
84 | 87 | }
|
85 | 88 | }
|
| 89 | + return start / s.length(); |
86 | 90 | }
|
87 |
| - return start / s.length(); |
88 | 91 | }
|
89 |
| - |
90 | 92 | }
|
0 commit comments