【bilibilli】翻转字符串

约定不等于承诺〃 2022-11-28 13:24 247阅读 0赞

1. 题目描述

在这里插入图片描述
题目链接:翻转字符串

2. 题目分析

  1. 剑指offer的原题。在剑指offer中,采取的方法是:对字符串进行处理,将首尾的空格去掉,再对整个字符串进行翻转,再翻转每一个小字符串,最后处理多余的空格,返回即可
  2. 这里我采取的是双指针的做法,比较容易理解和书写。
  3. 我们先判断异常的字符串:if(s == null || s.length() == 0 || s.trim().length() == 0){ return ""; }
  4. 我们定义i、j,从字符串的后面开始遍历,当i遇到空格时,我们将i+1~j(这里的i指向空格)存入StringBuffer中,然后再跑i,遇到字母的时候停止,j = i
  5. 这个题需要注意的点:注意存入的是i+1~j、防止越界,每次判断i>=0

3. 题目代码

  1. import java.util.*;
  2. public class Main{
  3. public static void main(String[] args){
  4. Scanner scanner = new Scanner(System.in);
  5. String s = scanner.nextLine();
  6. s = reverseWords(s);
  7. System.out.print(s);
  8. }
  9. public static String reverseWords(String s) {
  10. if (s == null || s.length() == 0 || s.trim().length() == 0) {
  11. return "";
  12. }
  13. s = s.trim();
  14. StringBuffer buffer = new StringBuffer();
  15. int i = s.length() - 1;
  16. int j = s.length() - 1;
  17. while (i >= 0 && j >= 0) {
  18. while (i >= 0 && s.charAt(i) != ' ') {
  19. i--;
  20. }
  21. buffer.append(s.substring(i + 1, j + 1) + " ");
  22. while (i >= 0 && s.charAt(i) == ' ') {
  23. i--;
  24. }
  25. j = i;
  26. }
  27. return buffer.toString();
  28. }
  29. }

发表评论

表情:
评论列表 (有 0 条评论,247人围观)

还没有评论,来说两句吧...

相关阅读

    相关 字符串翻转操作

    字符串翻转操作 题目: 小华有两个长度不超过1000的字符串s和t,现在他想将两个字符串翻转后拼接在一起(将s和t分别翻转后,按照s在前t在后的顺序拼接

    相关 翻转字符串

    翻转字符串 字符串反转 题目分析 翻转字符串(2) 题目分析 字符串反转 来源:牛客网 链接:https://www.n

    相关 翻转字符串

    题目描述 牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的