-
Notifications
You must be signed in to change notification settings - Fork 16
/
SortingTheSentence.java
43 lines (38 loc) · 1.33 KB
/
SortingTheSentence.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.ArrayList;
import java.util.List;
public class SortingTheSentence {
public String sortSentence(String s) {
final List<Word> words = getWords(s);
words.sort(Word::compareTo);
final StringBuilder result = new StringBuilder();
for (Word word : words) {
result.append(word.val).append(' ');
}
return result.deleteCharAt(result.length() - 1).toString();
}
private List<Word> getWords(String s) {
StringBuilder word = new StringBuilder();
final List<Word> words = new ArrayList<>();
for (int index = 0 ; index < s.length() ; index++) {
if (Character.isDigit(s.charAt(index))){
words.add(new Word(word.toString(), s.charAt(index) - '0'));
word = new StringBuilder();
} else if (s.charAt(index) != ' '){
word.append(s.charAt(index));
}
}
return words;
}
private static final class Word implements Comparable<Word> {
private final String val;
private final int position;
private Word(String val, int position) {
this.val = val;
this.position = position;
}
@Override
public int compareTo(Word o) {
return Integer.compare(this.position, o.position);
}
}
}