java: add «151. Reverse Words in a String»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
e5b9d8aa1c
commit
3c34c8b3db
1 changed files with 16 additions and 0 deletions
16
java/reverse-words-in-a-string.java
Normal file
16
java/reverse-words-in-a-string.java
Normal file
|
@ -0,0 +1,16 @@
|
|||
class Solution {
|
||||
private static <T> void reverse(T[] arr) {
|
||||
for (int l = 0, r = arr.length - 1; l < r; ++l, --r) {
|
||||
var tmp = arr[l];
|
||||
arr[l] = arr[r];
|
||||
arr[r] = tmp;
|
||||
}
|
||||
}
|
||||
|
||||
public String reverseWords(String s) {
|
||||
String[] words = s.strip().split("\\s+");
|
||||
reverse(words);
|
||||
|
||||
return String.join(" ", words);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue