给句子排序

给句子排序

  • 示例 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=2413,重新排序后变为1302
            //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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值