public String reverseWords(String s) { if (null == s || s.length() == 0) return""; finalchar[] c = s.toCharArray(); finalintlen= c.length; inti= len - 1; //去掉末尾的空格 while (i >= 0 && c[i] == ' ') i--;
intleft= i + 1; intright= i + 1; StringBuffersb=newStringBuffer(i + 1); for (; i >= 0; i--) { if (c[i] == ' ') { if (right != left) //左不等于右是为了判断没有空格 sb.append(c, left, right - left).append(" "); //加入单词 left = i; right = i; //调整指针位置 continue; } left = i; //往前找到不为空格的位置 } if (right != left) return sb.append(c, left, right - left).toString(); return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : ""; }