给句子排序
- 示例 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” ,然后删除数字
提示:
1. 2 <= s.length <= 200
2. s 只包含小写和大写英文字母、空格以及从 1 到 9 的数字。
3. s 中单词数目为 1 到 9 个。
4. s 中的单词由单个空格分隔。
5. s 不包含任何前导或者后缀空格
//实现方式
class Solution {
public String sortSentence(String s) {
String result ="";
StringBuffer a = new StringBuffer();
//把句子按空格split后放入str数组,
String[] str = s.split(" ");
//新数组用来存排序后
String[] sortedWords = new String[str.length];
for (int i = 0; i < str.length; i++) {
//遍历取数组中str[i]的最后一位
int index = Integer.parseInt(str[i].substring(str[i].length() - 1));
//👍👍最重要的一点是运用数组遍历重新排序
//下面的句子为例,index=2,4,1,3,重新排序后变为1,3,0,2
//index-1,主要是因为后一个数组重新遍历时不要超出范围
sortedWords[index - 1] = str[i].substring(0, str[i].length() - 1);
for(int i = 0; i < sortedWords.length; i++){
result = a.append(sortedWords[i]+" ").toString();
}
result = result.substring(0,result.length()-1);
return result;
}
}
句子 is2 sentence4 This1 a3