Java simple recursive solution

interview-questions
amazon
Tags: #<Tag:0x00007f242507b728> #<Tag:0x00007f242507b5c0>

#1
public class Solution {
    public String solve(String A) {
        String sb = new String();
        int n = A.length();
        int  i = n-1,j=n-1,k;
        
        //base case: if the length of string is zero return the string
        if(n == 0){
            return A;
        }
        
        //trimming the last zeroes. can be done with trim() also
        while(i>=0){
            if(A.charAt(i) == ' '){
                i--;
            }else break;
        }
        //assigning another pointer to traverse the word
        j = i;
        
        //traversing the word
        while(j>=0){
            if(A.charAt(j) != ' '){
                j--;
            }else break;
        }
        //since j points the character before the first letter of the word
        j++;
        //creating a string of the word
        k = j;
        while(k<=i){
            sb = sb+A.charAt(k);
            k++;
        }
        //recursion for the remaining part of the string
        sb = sb.toString() +' '+ solve(A.substring(0,j));
        //trimming applies after base case has reached and returns nothing
        //so removing the attached space;
        return sb.trim();
    }
}