Easy java solution using stringbuffer


#1
public class Solution {
    public String solve(String A) {
        StringBuffer res = new StringBuffer();
        boolean en = false;
        int j = A.length()-1;
        while(j >=0 ){
            
            int s = 0;
            int e = 0;
            
            while(j >=0 && A.charAt(j) == ' '){
                j = j-1;
            }
            e = j;
           // System.out.println(e);
            while(j>=0 && A.charAt(j) != ' '){
                j = j-1;
            }
            if(j>=0 && A.charAt(j) == ' '){
             s = j+1;   
            }else if(j<0 && A.charAt(0) != ' '){
                s = 0;
            }else{
                s = j;
            }
            //System.out.println(s);
            if(s <=e && s>=0 && e>=0){
            //    System.out.println(true);
                if(en){
                res.append(" ");
                }
                for(int i = s;i<=e;i++){
                res.append(A.charAt(i));
               // System.out.println(A.charAt(i));
            }
            }
            
            en = true;
            
        }
        
        return res.toString();
    }
}