leetcode 557. Reverse Words in a String III(字符串中单词逆序III)

本文介绍了一种方法,用于反转字符串中每个单词内字符的顺序,同时保持单词和空白符的原始顺序不变。提供了两种实现方案:一种使用split方法分割单词并利用StringBuilder进行反转;另一种采用双指针技术直接在字符数组上操作,无需额外分割。

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

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: s = “Let’s take LeetCode contest”
Output: “s’teL ekat edoCteeL tsetnoc”
Example 2:

Input: s = “God Ding”
Output: “doG gniD”

以空格分割单词,返回每个单词逆序之后的字符串。

思路:

方法1:
先用split分割单词,每个单词利用StringBuilder中的逆序函数进行逆序,
再拼接起来即可。
能通过,但是时间排名比较偏后。

public String reverseWords(String s) {
    String[] words = s.split(" ");
    
    for(int i = 0; i < words.length; i++)
        words[i] = (new StringBuilder(words[i])).reverse().toString();
    
    return String.join(" ", words);
}

方法2:
双指针

不需要用split分割单词,
用尾指针不断移动,指向空格 或者 字符串终点时 说明到达一个单词的结尾。
逆序就是首尾字母互换,用双指针一个指头一个指尾。
字符串直接是不能操作的,先转为char数组。

public String reverseWords(String s) {
    int n = s.length();
    char[] words = s.toCharArray();
    int start = 0;
    
    for(int end = 0; end <= n; end++) {
        if(end == n || words[end] == ' ') {
            reverse(start, end-1,  words);
            start = end + 1;
        }           
    }
    
    return new String(words);
}

void reverse(int start, int end, char[] arr) {
    while(start < end) {
        char tmp = arr[start];
        arr[start] = arr[end];
        arr[end] = tmp;
        start ++;
        end --;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蓝羽飞鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值