image.png

解决思路

image.png

  1. public class Solution {
  2. public String reverseWords(String s) {
  3. String words[] = s.split(" ");
  4. StringBuilder res=new StringBuilder();
  5. for (String word: words)
  6. res.append(new StringBuffer(word).reverse().toString() + " ");
  7. return res.toString().trim();
  8. }
  9. }

image.png

  1. public class Solution {
  2. public String reverseWords(String input) {
  3. final StringBuilder result = new StringBuilder();
  4. final StringBuilder word = new StringBuilder();
  5. for (int i = 0; i < input.length(); i++) {
  6. if (input.charAt(i) != ' ') {
  7. word.append(input.charAt(i));
  8. } else {
  9. result.append(word.reverse());
  10. result.append(" ");
  11. word.setLength(0);
  12. }
  13. }
  14. result.append(word.reverse());
  15. return result.toString();
  16. }
  17. }