先将每个单词翻转,然后再将整个字符数组翻转
char[] s = {am. I}
每个单词翻转
char[] s = {.ma I}
整个翻转 char[] s = {I am.}
public String ReverseSentence(String str) { int n = str.length(); int i = 0, j = 0; char[] s = str.toCharArray(); while(j <= n){ if(j == n || s[j] == ' '){ reverse(s,i,j-1); i = j+1; } j++; } reverse(s,0,n-1); return new String(s); } public void reverse(char[] s,int i, int j){ while(i<j) swap(s,i++,j--); } public void swap(char[] s,int i, int j){ char tmp = s[i]; s[i] = s[j]; s[j] = tmp; }