LeetCode知识点总结 - 1859

LeetCode 1859. Sorting the Sentence

考点难度
SortingEasy
题目

A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.

A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence.

For example, the sentence “This is a sentence” can be shuffled as “sentence4 a3 is2 This1” or “is2 sentence4 This1 a3”.
Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence.

思路

先split,找到每个string的编号,存到array的对应位置。再从array里依次提取string加到stringbuilder里面。

答案
public String sortSentence(String s) {
        String[] str = s.split(" ");               
		String[] res = new String[str.length];      
		StringBuilder sb = new StringBuilder();    
		int i = 0;                          
		for (String elem : str) {
			i = (int) (elem.charAt(elem.length() - 1) - '0');  
			res[i - 1] = elem.substring(0, elem.length() - 1); 
		}
		for (i = 0; i < res.length - 1; i++)
			sb.append(res[i]).append(" ");
			sb.append(res[i]);
		return sb.toString();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值