def solution(words: str) -> list:
word_list = [w[::-1] for w in words.split(' ')]
word_list.sort()
return [w[::-1] for w in word_list]
assert solution("man i need a taxi up to ubud") == ["a", "need", "ubud", "i", "taxi", "man", "to", "up"]
assert solution("take me to semynak") == ["take", "me", "semynak", "to"]
assert solution("massage yes massage yes massage") == ["massage", "massage", "massage", "yes", "yes"]
import java.util.Arrays;
public class SortByLastChar {
public static void main(String[] args) {
String[] words = {"man i need a taxi up to ubud", "take me to semynak", "massage yes massage yes massage"};
for (String word : words) {
String[] wordsList = new SortByLastChar().sortByLastChar(word);
System.out.println(word + " ->" + Arrays.deepToString(wordsList));
}
}
public String[] sortByLastChar(String words) {
String[] wordsList = words.split(" ");
String[] sortByLastCharList = new String[wordsList.length];
//生成最后一个字母 + 序号
for (int i = 0; i < wordsList.length; i++) {
sortByLastCharList[i] = wordsList[i].substring(wordsList[i].length() - 1) + i;
}
//按照最后一个字母排序
Arrays.sort(sortByLastCharList);
//生成新的字符串
for (int i = 0; i < wordsList.length; i++) {
int j = new Integer(sortByLastCharList[i].substring(1));
sortByLastCharList[i] = wordsList[j];
}
return sortByLastCharList;
}
}
def solution(words:str):
new_list = words.split(' ')
new = []
for i in new_list:
new.append(i[-1])
new.sort()
words_list = []
for i in new:
for j in new_list:
if j[-1] == i:
words_list.append(j)
new_list.remove(j)
break
return words_list
assert solution("man i need a taxi up to ubud") == ["a", "need", "ubud", "i", "taxi", "man", "to", "up"]
assert solution("take me to semynak") == ["take", "me", "semynak", "to"]
assert solution("massage yes massage yes massage") == ["massage", "massage", "massage", "yes", "yes"]