题目来源:
leetcode题目,网址:1859. 将句子排序 - 力扣(LeetCode)
解题思路:
首先将字符串根据空格分割成字符串数组,然后根据最后一个字符对字符串数组进行排序,接着在不包含每个字符串最后一个字符的情况下进行重新拼接,最后按要求返回即可。
解题代码:
class Solution {
public String sortSentence(String s) {
String[] split=s.split(" ");
Arrays.sort(split,new Comparator<>(){
public int compare(String a,String b){
return a.charAt(a.length()-1)-b.charAt(b.length()-1);
}
});
StringBuffer res=new StringBuffer();
for(int i=0;i<split.length-1;i++){
res.append(split[i].substring(0,split[i].length()-1));
res.append(" ");
}
res.append(split[split.length-1].substring(0,split[split.length-1].length()-1));
return res.toString();
}
}
总结:
官方题解是在新建数组后,遍历字符串并根据数字将对应字字符串放入对应位置,最后拼接并返回。
trailing adj.拖尾的
shuffle v.洗牌、搬移