class Solution {
public String reverseWords(String s) {
StringBuilder sb=removeSpace(s);
reverse(sb,0,sb.length()-1);
reverseEach(sb);
return sb.toString();
}
public StringBuilder removeSpace(String s)
{
int start=0;
int end=s.length()-1;
while(s.charAt(start)==' ') start++;
while(s.charAt(end)==' ') end--;
StringBuilder sb=new StringBuilder();
while(start<=end)
{
char c=s.charAt(start);
if(c!=' '||sb.charAt(sb.length()-1)!=' ')
{
sb.append(c);
}
start++;
}
return sb;
}
public void reverse(StringBuilder sb,int start,int end)
{
while(start<end)
{
char temp=sb.charAt(start);
sb.setCharAt(start,sb.charAt(end));
sb.setCharAt(end,temp);
start++;
end--;
}
}
public void reverseEach(StringBuilder sb)
{
int start=0;
int end=1;
while(start<sb.length())
{
while(end<sb.length()&&sb.charAt(end)!=' ')
{
end++;
}
reverse(sb,start,end-1);
start=end+1;
end=start+1;
}
}
}