「这是我参与2022首次更文挑战的第1天,活动详情查看:2022首次更文挑战」
今天才知道sort排序有多么不稳定,以后改用stable_sort了
——leetcode此题热评
前言
大家好,我是一条,欢迎来到我的算法频道。
只做有趣的算法题,只为面试写算法。
Question
1451. 重新排列句子中的单词
难度:中等
「句子」是一个用空格分隔单词的字符串。给你一个满足下述格式的句子 text :
句子的首字母大写 text 中的每个单词都用单个空格分隔。 请你重新排列 text 中的单词,使所有单词按其长度的升序排列。如果两个单词的长度相同,则保留其在原句子中的相对顺序。
请同样按上述格式返回新的句子。
示例 :
输入:text = "Keep calm and code on" 输出:"On and keep calm code" 解释:输出的排序情况如下: "On" 2 个字母。 "and" 3 个字母。 "keep" 4 个字母,因为存在长度相同的其他单词,所以它们之间需要保留在原句子中的相对顺序。 "calm" 4 个字母。 "code" 4 个字母。
text以大写字母开头,然后包含若干小写字母以及单词间的单个空格。1 <= text.length <= 10^5
Solution
本题看上去不难,关键在于这句话:如果两个单词的长度相同,则保留其在原句子中的相对顺序。
如何保证相对顺序,两种办法:
- 使用不会改变相对顺序的排序算法。
- 排序前做处理,就不再考虑使用什么排序算法。
排序前处理:
首先想到哈希表,用字符的长度做key,值做value。遍历时如果key已经存在,则把两个字符连接在一起。同时为了排序之后能再分开,将value改为存储值+空格。
排序算法:
相信很多人都想到了Arrays.sort,但是细看源码会发现其底层使用的排序方式会根据阈值(数组的长度)发生变化,充分利用各排序算法的特性。所以其很不稳定。
最后改为用Comparator实现。
别忘了首字母要大写。
Code
M1
/**
* @author 一条coding
*/
class Solution {
public String arrangeWords(String text) {
String[] words = text.toLowerCase().split(" ");
Arrays.sort(words, Comparator.comparingInt(String::length));
words[0] = words[0].substring(0, 1).toUpperCase() + words[0].substring(1);;
return String.join(" ", words);
}
}
M2
/**
* @author 一条coding
*/
class Solution {
public String arrangeWords(String text) {
StringBuilder sb = new StringBuilder();
Map<Integer, String> map = new HashMap<>();
// 首字母转换为小写
text = text.substring(0, 1).toLowerCase() + text.substring(1);
//添加到map中
String[] texts = text.split(" ");
for (String s : texts) map.put(s.length(), map.getOrDefault(s.length(), "") + s + " ");
//遍历键
int[] keys = new int[map.size()];
int idx = 0;
for (Integer key : map.keySet()) keys[idx++] = key;
Arrays.sort(keys);
for (int key : keys) sb.append(map.get(key));
// 首字母转换为大写
String res = sb.toString();
res = res.substring(0, 1).toUpperCase() + res.substring(1, res.length() - 1);
return res;
}
}
最后
点赞,点赞,还TMD是点赞!