Leetcode5742. 将句子排序

Posted !0 !

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode5742. 将句子排序相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode-cn.com/problems/sorting-the-sentence/

解题思路

先用split把所有单词分开存储到str字符串数组中,因为单词最多只有9个,所以我们可以用一个str1字符串数组存储排序之后的单词。最后连接在一起就是答案。

代码

class Solution {
    public String sortSentence(String s) {
        String[] str = s.split(" ");    //句子分解成单词
        String[] str1 = new String[10]; //存储排序之后的答案
        for(int i = 0; i < str.length; i++)     //将每个单词的最后一个数字当作下标存储到str1中,因为最后的答案不包含数字,所以要把数字去除
            str1[str[i].charAt(str[i].length() - 1) - '0'] = str[i].substring(0, str[i].length() - 1);
        String ans = "";    //最终连接成句子的答案
        for(int i = 1; i <= str.length; i++) {  //把单词连接成句子
            ans += str1[i];
            if(i != str.length)
                ans += " ";
        }
        return ans;
    }
}

复杂度分析

  • 时间复杂度:O(n)
  • 空间复杂度:O(n)

以上是关于Leetcode5742. 将句子排序的主要内容,如果未能解决你的问题,请参考以下文章