Member-only story

Leetcode 1451: Rearrange Words in a Sentence

Pierre-Marie Poitevin
2 min readMay 26, 2020

--

In this Leetcode problem, we rearrange the words in a sentence given a couple of rules:

  • Words with fewer letter are first
  • If words have the same number of letters, they keep their original order in the sentence
Problem statement

Solution

This is mostly an ordering problem. To solve this, we define a Comparable class Word containing the word string and the order in the original sentence.

class Word implements Comparable<Word> {
String s;
int ord;

Word(String s, int ord) {
this.s = s;
this.ord = ord;
}

public int compareTo(Word w) {
int sn = s.length();
int wn = w.s.length();
if (sn < wn) {
return -1;
} else if (sn > wn) {
return 1;
} else if (ord < w.ord) {
return -1;
} else if (ord > w.ord) {
return 1;
}
return 0;
}
}

The compareTo method follows the rules laid down by the problem statement.

Then, we use Collections.sort to sort all the words. Before that we need to parse the words out out of the original sentence. That is down by simply splitting the string and looping through the resulting array.

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

Responses (1)