LeetCode每日一题(1451. Rearrange Words in a Sentence)

Given a sentence text (A sentence is a string of space-separated words) in the following format:

First letter is in upper case.
Each word in text are separated by a single space.
Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.

Return the new text following the format shown above.

Example 1:

Input: text = “Leetcode is cool”
Output: “Is cool leetcode”

Explanation: There are 3 words, “Leetcode” of length 8, “is” of length 2 and “cool” of length 4.
Output is ordered by length and the new first word starts with capital letter.

Example 2:

Input: text = “Keep calm and code on”
Output: “On and keep calm code”

Explanation:
Output is ordered as follows:
“On” 2 letters.
“and” 3 letters.
“keep” 4 letters in case of tie order by position in original text.
“calm” 4 letters.
“code” 4 letters.

Example 3:

Input: text = “To be or not to be”
Output: “To be or to be not”

Constraints:

  • text begins with a capital letter and then contains lowercase letters and single space between words.
  • 1 <= text.length <= 10^5

长度不同按长度排, 长度相同按 index 排

rust 处理字符串的能力真的很让人不爽,有种相声演员报菜名,哪哪都挺流利, 就是说到某道菜就变结巴的感觉



impl Solution {
    pub fn arrange_words(text: String) -> String {
        let mut words: Vec<((usize, usize), String)> = text
            .split(" ")
            .enumerate()
            .map(|(i, w)| ((w.len(), i), w.to_lowercase()))
            .collect();
        words.sort_by_key(|w| w.0);
        let mut words: Vec<String> = words.into_iter().map(|((_, _), w)| w).collect();
        let mut first_word = words[0].chars().collect::<Vec<char>>();
        first_word[0] = first_word[0].to_uppercase().nth(0).unwrap();
        words[0] = first_word.into_iter().collect();
        words.join(" ")
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值