LeetCode : Reverse Words in a String III (Java Solution).
Java Solution for reverse words in a string form leetcode.
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: s = "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Example 2:
Input: s = "God Ding" Output: "doG gniD"
class Solution {
public String reverseWords(String s) {
return Arrays.stream(s.split(" "))
.map(word -> new StringBuilder(word).reverse().toString())
.collect(Collectors.joining(" "));
}
}
Another Solution
class Solution {
public String reverseWords(String s) {
String[] arr = s.split(" ");
String ans = "";
for(int i=0;i<arr.length;i++)
ans += reverse(arr[i])+((i==arr.length-1)?"":" ");
return ans;
}
static String reverse(String s){
return new String(new StringBuffer(s).reverse());
}
}
