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 sentences containing no more than 9 words, reconstruct and return the original sentence.
Input: s ="is2 sentence4 This1 a3" Output:"This is a sentence" Explanation: Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers.
Input: s ="Myself2 Me1 I4 and3" Output:"Me Myself and I" Explanation: Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers.
Intuition: Since each word has a number (1-9) indicating its position, we can directly place each word in the correct position in an array and then join them.
Approach:
Split the input string into words
Create an array of size equal to number of words
For each word, extract the last character (position number) and place the word (without the number) at that position
classSolution {
public String sortSentence(String s) {
String[] words = s.split(" ");
String[] result =new String[words.length];
for (String word : words) {
int pos = word.charAt(word.length() - 1) -'1'; // Convert to 0-indexed result[pos]= word.substring(0, word.length() - 1); // Remove the number }
return String.join(" ", result);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funsortSentence(s: String): String {
val words = s.split(" ")
val result = Array(words.size) { "" }
for (word in words) {
val pos = word.last().digitToInt() - 1// Convert to 0-indexed
result[pos] = word.dropLast(1) // Remove the number
}
return result.joinToString(" ")
}
}
1
2
3
4
5
6
7
8
9
defsortSentence(s: str) -> str:
words = s.split()
result = [''] * len(words)
for word in words:
pos = int(word[-1]) -1# Convert to 0-indexed result[pos] = word[:-1] # Remove the numberreturn' '.join(result)
1
2
3
4
5
6
7
8
9
10
11
pubfnsort_sentence(s: String) -> String {
let words: Vec<&str>= s.split_whitespace().collect();
letmut result =vec![String::new(); words.len()];
for word in words {
let pos = word.chars().last().unwrap().to_digit(10).unwrap() asusize-1;
result[pos] = word[..word.len()-1].to_string();
}
result.join(" ")
}
1
2
3
4
5
6
7
8
9
10
11
functionsortSentence(s: string):string {
constwords=s.split(' ');
constresult: string[] =new Array(words.length);
for (constwordofwords) {
constpos= parseInt(word[word.length-1]) -1; // Convert to 0-indexed
result[pos] =word.slice(0, -1); // Remove the number
}
returnresult.join(' ');
}