LeetCode 1859. Sorting the Sentence
考点 | 难度 |
---|---|
Sorting | Easy |
题目
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();
}