1859:将句子排序

This commit is contained in:
huangge1199 2021-06-07 13:08:04 +08:00
parent 8cfc0007b8
commit 0d44c7d2d3
2 changed files with 117 additions and 0 deletions

View File

@ -0,0 +1,78 @@
//一个 句子 指的是一个序列的单词用单个空格连接起来且开头和结尾没有任何空格每个单词都只包含小写或大写英文字母
//
// 我们可以给一个句子添加 1 开始的单词位置索引 并且将句子中所有单词 打乱顺序
//
//
// 比方说句子 "This is a sentence" 可以被打乱顺序得到 "sentence4 a3 is2 This1" 或者 "is2 senten
//ce4 This1 a3"
//
//
// 给你一个 打乱顺序 的句子 s 它包含的单词不超过 9 请你重新构造并得到原本顺序的句子
//
//
//
// 示例 1
//
//
//输入s = "is2 sentence4 This1 a3"
//输出"This is a sentence"
//解释 s 中的单词按照初始位置排序得到 "This1 is2 a3 sentence4" 然后删除数字
//
//
// 示例 2
//
//
//输入s = "Myself2 Me1 I4 and3"
//输出"Me Myself and I"
//解释 s 中的单词按照初始位置排序得到 "Me1 Myself2 and3 I4" 然后删除数字
//
//
//
// 提示
//
//
// 2 <= s.length <= 200
// s 只包含小写和大写英文字母空格以及从 1 9 的数字
// s 中单词数目为 1 9
// s 中的单词由单个空格分隔
// s 不包含任何前导或者后缀空格
//
// Related Topics 排序 字符串
// 👍 0 👎 0
package leetcode.editor.cn;
import java.util.HashMap;
import java.util.Map;
//1859:将句子排序
public class SortingTheSentence{
public static void main(String[] args) {
//测试代码
Solution solution = new SortingTheSentence().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String sortSentence(String s) {
String[] strs = s.split(" ");
Map<Integer, String> map = new HashMap<>();
for (String str : strs) {
int num = Integer.parseInt(str.substring(str.length() - 1));
str = str.substring(0, str.length() - 1) + " ";
map.put(num, str);
}
s = "";
for (int i = 1; i < 10; i++) {
if (map.containsKey(i)) {
s += map.get(i);
} else {
break;
}
}
return s.substring(0, s.length() - 1);
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,39 @@
<p>一个 <strong>句子</strong> 指的是一个序列的单词用单个空格连接起来,且开头和结尾没有任何空格。每个单词都只包含小写或大写英文字母。</p>
<p>我们可以给一个句子添加 <strong>从 1 开始的单词位置索引 </strong>,并且将句子中所有单词 <strong>打乱顺序</strong> 。</p>
<ul>
<li>比方说,句子 <code>"This is a sentence"</code> 可以被打乱顺序得到 <code>"sentence4 a3 is2 This1"</code> 或者 <code>"is2 sentence4 This1 a3"</code> 。</li>
</ul>
<p>给你一个 <strong>打乱顺序</strong> 的句子 <code>s</code> ,它包含的单词不超过 <code>9</code> 个,请你重新构造并得到原本顺序的句子。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<b>输入:</b>s = "is2 sentence4 This1 a3"
<b>输出:</b>"This is a sentence"
<b>解释:</b>将 s 中的单词按照初始位置排序,得到 "This1 is2 a3 sentence4" ,然后删除数字。
</pre>
<p><strong>示例 2</strong></p>
<pre>
<b>输入:</b>s = "Myself2 Me1 I4 and3"
<b>输出:</b>"Me Myself and I"
<b>解释:</b>将 s 中的单词按照初始位置排序,得到 "Me1 Myself2 and3 I4" ,然后删除数字。</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>2 <= s.length <= 200</code></li>
<li><code>s</code> 只包含小写和大写英文字母、空格以及从 <code>1</code> 到 <code>9</code> 的数字。</li>
<li><code>s</code> 中单词数目为 <code>1</code> 到 <code>9</code> 个。</li>
<li><code>s</code> 中的单词由单个空格分隔。</li>
<li><code>s</code> 不包含任何前导或者后缀空格。</li>
</ul>
<div><div>Related Topics</div><div><li>排序</li><li>字符串</li></div></div>\n<div><li>👍 0</li><li>👎 0</li></div>