Reverse Words in a String III Leetcode Solution

Hello coders, I am here with another problem of Leetcode ” Reverse Words in a String III Leetcode Solution “. In this blog, we will see how to solve this Leetcode Problem within the time limit.

Problem Statement:

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

I hope you understand the problem statement, below are the examples to support the statement and help you to make an approach.

Example 1:

Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Example 2:

Input: s = "God Ding"
Output: "doG gniD"


Reverse Words in a String III Leetcode Solution

//Reverse Words in a String III Leetcode Solution
class Solution {
    public String reverseWords(String s) {
        char[] chars = s.toCharArray();
        
        int left = 0;
        int right = 0;
        
        while(right < chars.length) {
            if(chars[right] == ' ') {
                reverse(chars, left, right-1);
                left = right+1;
            } else if(right == chars.length-1) {
               reverse(chars, left, right); 
            }
            right++;
        }
        
        return new String(chars);
    }
    
    private void reverse(char[] chars, int left, int right) {
        for(left<right; left++, right--) {
            char temp = chars[right];
            chars[right] = chars[left];
            chars[left] = temp;
        }
    }
}
//Reverse Words in a String III Leetcode Solution

Disclaimer: This problem is originally created by Leetcode. Codesagar only provides a solution for it. This solution is only for Educational and learning purposes.

Leave a Comment