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

在这里插入图片描述

class Solution {
    public String reverseWords(String s) {
        s = s.trim(); // 删除首尾空格
        int j = s.length() - 1, i = j;
        StringBuilder res = new StringBuilder();
        while(i >= 0) {
            while(i >= 0 && s.charAt(i) != ' ') i--; // 搜索首个空格
            res.append(s.substring(i + 1, j + 1) + " "); // 添加单词
            while(i >= 0 && s.charAt(i) == ' ') i--; // 跳过单词间空格
            j = i; // j 指向下个单词的尾字符
        }
        return res.toString().trim(); // 转化为字符串并返回
    }
}

作者:jyd
链接: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/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
根据引用\[1\],题目是要求翻转一个英文句子中单词顺序,但保持单词内字符的顺序不变。例如,输入字符串"I am a student.",则输出"student. a am I"。 根据引用\[2\]和引用\[3\],提供了三种解法。解法1是通过字符串遍历的方式,将每个字符按照翻转后的位置重新拼接成一个新的字符串。解法2是通过字符串切分与拼接的方式,先将前n个字符切分出来,然后将剩余的字符与切分出来的字符进行拼接。解法3是通过三次翻转的方式,先翻转前n个字符,再翻转剩余的字符,最后再整体翻转整个字符串。 根据题目的要求,你可以选择其中一种解法来实现。 #### 引用[.reference_title] - *1* [剑指Offer58-Ⅰ—翻转单词顺序](https://blog.csdn.net/qq_39172845/article/details/124604122)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [剑指Offer58-Ⅱ—左旋转字符串](https://blog.csdn.net/qq_39172845/article/details/124625810)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值