【bilibilli】翻转字符串

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. 题目代码

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        s = reverseWords(s);
        System.out.print(s);
    }
    
    public static String reverseWords(String s) {
        if (s == null || s.length() == 0 || s.trim().length() == 0) {
            return "";
        }
        s = s.trim();
        StringBuffer buffer = new StringBuffer();
        int i = s.length() - 1;
        int j = s.length() - 1;
        while (i >= 0 && j >= 0) {
            while (i >= 0 && s.charAt(i) != ' ') {
                i--;
            }
            buffer.append(s.substring(i + 1, j + 1) + " ");
            while (i >= 0 && s.charAt(i) == ' ') {
                i--;
            }
            j = i;
        }
        return buffer.toString();
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱敲代码的小黄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值