Leetcode 557: Reverse Words in a String III

问题描述:

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
把单词(单词内部)逆序,整个字符串的词序不变,空格位置不变。
举例:
Input: s = “Let’s take LeetCode contest”
Output: “s’teL ekat edoCteeL tsetnoc”
限定条件:
1 <= s.length <= 5 * 10000
s contains printable ASCII characters.
s does not contain any leading or trailing spaces.
There is at least one word in s.
All the words in s are separated by a single space.

思路:
遍历字符串,如果某一位是空格,则在目标字符串中加入该元素;若某一位不是空格,则在一个临时的list中加入该元素,且这时如果下一位是空格,说明这段时间内在list上已经储存了一个完整单词,是时候把它倒序输出了,而且倒序输出后清空list

代码如下:

class Solution {
    public String reverseWords(String s) {
        s=s+" ";
        StringBuilder sb = new StringBuilder();
        List<Character> list = new ArrayList<>();
        for(int i=0; i<s.length()-1;i++){
            if(s.charAt(i)==' '){
                sb.append(s.charAt(i));
            }
            else{
                list.add(s.charAt(i));
                if(s.charAt(i+1)==' '){
                    for(int j=list.size()-1; j>=0; j--){
                        sb.append(list.get(j));
                    }
                    list.clear();
                }
            }
        }
        return sb.toString();
    }
}

时间复杂度:O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值