151. Reverse Words in a String
public class Solution { public String reverseWords(String s) { char[] arr=s.toCharArray(); reverse(arr, 0, arr.length-1); int i=0; int j=0; while(j<=arr.length) { if(j==arr.length||arr[j]==' ') { reverse(arr, i,j-1); j++; i=j; } else j++; } i=0; j=0; while(j<arr.length) { if(arr[j]==' '&&(j==0||arr[j-1]==' ')) j++; else { arr[i]=arr[j]; j++; i++; } } if(i>0&&i<=arr.length&&arr[i-1]==' ') i--; return new String(arr).substring(0,i); } private void reverse(char[] arr, int i, int j){ while(i<j) { char t=arr[i]; arr[i]=arr[j]; arr[j]=t; i++; j--; } } }