剑指 Offer 58 - I. 翻转单词顺序

双指针

  1. public String reverseWords(String s) {
  2. s = s.trim(); // 删除首尾空格
  3. int j = s.length() - 1, i = j;
  4. StringBuilder res = new StringBuilder();
  5. while(i >= 0) {
  6. while(i >= 0 && s.charAt(i) != ' ') i--; // 搜索首个空格
  7. res.append(s.substring(i + 1, j + 1) + " "); // 添加单词
  8. while(i >= 0 && s.charAt(i) == ' ') i--; // 跳过单词间空格
  9. j = i; // j 指向下个单词的尾字符
  10. }
  11. return res.toString().trim(); // 转化为字符串并返回
  12. }
  13. // 作者:jyd
  14. // 链接:https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/solution/mian-shi-ti-58-i-fan-zhuan-dan-ci-shun-xu-shuang-z/
  15. public String reverseWords2(String s) {
  16. String[] strs = s.trim().split(" "); // 删除首尾空格,分割字符串
  17. StringBuilder res = new StringBuilder();
  18. for(int i = strs.length - 1; i >= 0; i--) { // 倒序遍历单词列表
  19. if(strs[i].equals("")) continue; // 遇到空单词则跳过
  20. res.append(strs[i] + " "); // 将单词拼接至 StringBuilder
  21. }
  22. return res.toString().trim(); // 转化为字符串,删除尾部空格,并返回
  23. // 作者:jyd
  24. // 链接:https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/solution/mian-shi-ti-58-i-fan-zhuan-dan-ci-shun-xu-shuang-z/

s.substring(i,j) // [)