Reverse Words in a String III Java Solution - The Coding Shala

Home >> Interview Questions >> Reverse Words in a String 3

Reverse Words in a String III

Problem:

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



Example 1:

Input: "Let's take LeetCode contest"

Output: "s'teL ekat edoCteeL tsetnoc"



Note: In the string, each word is separated by a single space and there will not be any extra space in the string.

Reverse Words in a String III Java Solution

Approach 1:
Using StringBuilder and reverse we can do it.

Java 

class Solution {
    public String reverseWords(String s) {
        s = s.trim();
        int len = s.length()-1;
        StringBuilder ans = new StringBuilder();
        StringBuilder tmp = new StringBuilder();
        int i = 0;
        while(i<=len){
            if(s.charAt(i)==' '){
                tmp.reverse();
                ans.append(tmp).append(" ");
                tmp=new StringBuilder();
                while(i<=len && s.charAt(i)==' ') i++;
            }else{
                tmp.append(s.charAt(i)); 
                i++;
            }
        }
        tmp.reverse();
        ans.append(tmp);
        return ans.toString();
    }
}

Approach 2:
We can convert String into a char array and then reverse the char till space.

Java 

class Solution {
    public String reverseWords(String s) {
        s = s.trim();
        char[] ans = s.toCharArray();
        int i = 0, j = s.length(),tmp=0;
        while(i<j){
            if(ans[i]==' '){
                reverse(ans, tmp, i-1);
                tmp = i+1;
            }
            i++;
        }
        reverse(ans, tmp, j-1);
        return new String(ans);
    }
    
    public void reverse(char[] ans, int start, int end){
        while(start<end){
           char t = ans[start];
            ans[start] = ans[end];
            ans[end] = t;
            start++;
            end--;
        }
    }
}



Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Single Number 3 LeetCode Solution - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala