剑指offer第42题:单词反转

本文介绍了一种在时间复杂度O(n)和空间复杂度O(1)下实现字符数组单词翻转的方法,通过两次反转操作达到单词的倒序排列效果。例如,将Areyoureadynow.转换为now.readyyouAre。

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

输入:字符数组;
输出:字符数组;转换规则:单词(非空格字符认为是单词构成)翻转,即最后一个单词在前,第一个单词在后,如此倒转。要求:时间复杂度O(n),时间复杂度O(1),即char[]原地转换。​
eg:输入"Are you ready now.",输出"now. ready you Are"
思路:两次反转

public class Reverse {

    char space = ' ';

    public char[] reverseAll(char[] ch){
        if(ch == null || ch.length == 0){
            return ch;
        }
        reverse(ch, 0, ch.length-1);
        int begin = 0;
        int last = 0;
        while (begin < ch.length){
            if(ch[begin] == space){
                begin ++;
                last ++;
            } else if(last == ch.length || ch[last] == space){
//                last == ch.length必须写前面,否则数组越界异常
                reverse(ch,begin,-- last);
                begin = ++ last;
            } else {
                last ++;
            }
        }
        return ch;
    }

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

    public static void main(String[] args) {
        String Str = "Are you ready now";
        System.out.println(new String(new Reverse().reverseAll(Str.toCharArray())));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值