Q37 LeetCode151 反转字符串中的单词
index工作指针 left、right边界指针
1 class Solution { 2 public String reverseWords(String s) { 3 char[] string=s.toCharArray(); 4 int left=0; 5 int right=s.length()-1; 6 while(string[left]==' '){ 7 left++; 8 } 9 // 清除右边 10 while(string[right]==' '){ 11 right--; 12 } 13 StringBuffer sb=new StringBuffer(); 14 while(left<=right){ 15 int index=right; 16 while(index>=left&&string[index]!=' '){ 17 index--; 18 } 19 for(int j=index+1;j<=right;j++){ 20 sb.append(string[j]); 21 } 22 if(index>left){ 23 sb.append(" "); 24 } 25 while(index>=left&&string[index]==' '){ 26 index--; 27 } 28 right=index; 29 } 30 return sb.toString(); 31 } 32 }