151. Reverse Words in a String

本文介绍了一种用于按单词反转字符串的算法实现,并提供了两种不同难度级别的解决方案:一种允许额外空间分配,另一种则要求在原地操作,即不使用额外的空间。文章通过具体的代码示例详细解释了每一步的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an input string, reverse the string word by word.
For example,

Given s = "the sky is blue",

return "blue is sky the”. 

按单词反转字符串 按照空格分割单词 重新倒序拼接就可以了

public String reverseWords(String s) {
        String[] array = s.split(" ");
        StringBuilder res = new StringBuilder();
        for(int i=array.length-1; i>=0; i--) {
            if(array[i].isEmpty()) continue;
            res.append(array[i]);
            res.append(" ");
        }
        if (res.length() == 0) return res.toString();
        else return res.toString().substring(0, res.length()-1);
    }

对应的  

186. Reverse Words in a String II 增加了一个限制

Could you do it in-place without allocating extra space?

要求不额外开辟空间 感觉不是很好想 类似 

这种reverse或者rotate 并要求in-place的 多想想两步完成 

public void reverseWords(char[] s) {
    // Three step to reverse
    // 1, reverse the whole sentence
    reverse(s, 0, s.length - 1);
    // 2, reverse each word
    int start = 0;
    int end = -1;
    for (int i = 0; i < s.length; i++) {
        if (s[i] == ' ') {
            reverse(s, start, i - 1);
            start = i + 1;
        }
    }
    // 3, reverse the last word, if there is only one word this will solve the corner case
    reverse(s, start, s.length - 1);
}

public void reverse(char[] s, int start, int end) {
    while (start < end) {
        char temp = s[start];
        s[start] = s[end];
        s[end] = temp;
        start++;
        end--;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值