-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRearrangeWordsInASentence.java
More file actions
44 lines (43 loc) · 1.33 KB
/
RearrangeWordsInASentence.java
File metadata and controls
44 lines (43 loc) · 1.33 KB
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
44
class Solution {
static class Pair implements Comparable<Pair> {
String str;
int length;
int index;
public Pair(String str, int length, int index) {
this.str = str;
this.length = length;
this.index = index;
}
@Override
public int compareTo(Pair p2) {
if (this.length != p2.length) {
return this.length - p2.length;
}
return this.index - p2.index;
}
}
public String arrangeWords(String text) {
PriorityQueue<Pair> pq = new PriorityQueue<>();
String[] arr = text.split(" ");
for (int i = 0; i < arr.length; i++) {
pq.add(new Pair(arr[i], arr[i].length(), i));
}
StringBuilder sb = new StringBuilder();
boolean isFirstWord = true;
while (!pq.isEmpty()) {
Pair current = pq.poll();
String word = current.str;
if (isFirstWord) {
word = word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
isFirstWord = false;
} else {
word = word.toLowerCase();
}
sb.append(word);
if (!pq.isEmpty()) {
sb.append(" ");
}
}
return sb.toString();
}
}