java: add «151. Reverse Words in a String»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-12 18:28:54 +02:00
parent e5b9d8aa1c
commit 3c34c8b3db
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View 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);
}
}