Skip to content

Commit 6c4124b

Browse files
solves truncate sentences
1 parent 9bc28dd commit 6c4124b

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,7 @@
441441
| 1800 | [Maximum Ascending Subarray Sum](https://leetcode.com/problems/maximum-ascending-subarray-sum) | [![Java](assets/java.png)](src/MaximumAscendingSubArraySum.java) | |
442442
| 1805 | [Number of Different Integers in a String](https://leetcode.com/problems/number-of-different-integers-in-a-string) | [![Java](assets/java.png)](src/NumberOfDifferentIntegersInString.java) | |
443443
| 1812 | [Determine Color of a Chessboard Square](https://leetcode.com/problems/determine-color-of-a-chessboard-square) | [![Java](assets/java.png)](src/DetermineColorOfChessboardSquare.java) | |
444-
| 1816 | [Truncate Sentence](https://leetcode.com/problems/truncate-sentence) | | |
444+
| 1816 | [Truncate Sentence](https://leetcode.com/problems/truncate-sentence) | [![Java](assets/java.png)](src/TruncateSentences.java) | |
445445
| 1822 | [Sign of the Product of an Array](https://leetcode.com/problems/sign-of-the-product-of-an-array) | | |
446446
| 1826 | [Faulty Sensor](https://leetcode.com/problems/faulty-sensor) | | |
447447
| 1827 | [Minimum Operations to Make the Array Increasing](https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing) | | |

src/TruncateSentences.java

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
public class TruncateSentences {
2+
public String truncateSentence(String s, int k) {
3+
final StringBuilder result = new StringBuilder();
4+
for (int index = 0, words = 0 ; index < s.length() && words < k ; index++) {
5+
if (s.charAt(index) != ' ') {
6+
result.append(s.charAt(index));
7+
} else {
8+
words++;
9+
result.append(words < k ? ' ' : "");
10+
}
11+
}
12+
return result.toString();
13+
}
14+
}

0 commit comments

Comments
 (0)