Sorting the Sentence

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
    def sortSentence(self, s: str) -> str:
        strings = s.split(" ")                
        rearranged = [None]*len(strings)              
        result = []                        

        for string in strings:
            i = int(string[-1])  
            rearranged[i - 1] = string[:-1] 

        for i in range(len(rearranged) - 1):
            result.append(rearranged[i])
            result.append(" ")
        result.append(rearranged[-1])

        return ''.join(result)

In this code:

  1. We split the input string s into words and store them in strings.
  2. For each string in strings, we extract the last character, which is the index. We convert it to an integer and use it as an index to place the string (without the last character) into the correct position in the rearranged list.
  3. We join the words in the rearranged list into a string, with spaces between each word. This is stored in the result list.
  4. Finally, we join the result list into a string and return it.