Reverse Words in a String III

Reverse Words in a String III

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

LeetCode Problem - 557: Link | Click Here

class Solution {
    public String reverseWords(String s) {
        // StringBuilder to store the reversed words
        StringBuilder sb1 = new StringBuilder();

        // Split the input string into an array of words
        String[] splitString = s.split(" ");

        // Iterate through each word in the array
        for (int i=0; i<splitString.length; i++){
            // Reverse the current word
            String reverseChar = reverseChar(splitString[i]);

            // Append the reversed word to the StringBuilder
            if (i==(splitString.length-1)){
                // If it's the last word, append without space
                sb1.append(reverseChar);
            }
            else {
                // If not the last word, append with a space
                sb1.append(reverseChar).append(" ");
            }
        }

        // Convert the StringBuilder to a string and return
        return sb1.toString();
    }

    // Function to reverse a given string
    static String reverseChar(String c){
        // StringBuilder to store the reversed string
        StringBuilder sb2 = new StringBuilder();

        // Iterate through each character in the string in reverse order
        for (int i=c.length()-1; i>=0; i--){
            // Append the current character to the StringBuilder
            sb2.append(c.charAt(i));
        }

        // Convert the StringBuilder to a string and return
        return sb2.toString();
    }
}