-
Notifications
You must be signed in to change notification settings - Fork 1
/
Day 23.2.txt
88 lines (74 loc) · 2.33 KB
/
Day 23.2.txt
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
1451. Rearrange Words in a Sentence
Given a sentence text (A sentence is a string of space-separated words) in the following format:
First letter is in upper case.
Each word in text are separated by a single space.
Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.
Return the new text following the format shown above.
Example 1:
Input: text = "Leetcode is cool"
Output: "Is cool leetcode"
Explanation: There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.
Output is ordered by length and the new first word starts with capital letter.
Example 2:
Input: text = "Keep calm and code on"
Output: "On and keep calm code"
Explanation: Output is ordered as follows:
"On" 2 letters.
"and" 3 letters.
"keep" 4 letters in case of tie order by position in original text.
"calm" 4 letters.
"code" 4 letters.
Example 3:
Input: text = "To be or not to be"
Output: "To be or to be not"
Constraints:
text begins with a capital letter and then contains lowercase letters and single space between words.
1 <= text.length <= 10^5
class Solution {
public String arrangeWords(String t) {
t=t.trim();
String k[]=new String[t.length()];
int i,p=0,m=0,du;
String d="";
for(i=1;i<t.length();i++)
{
if(t.charAt(i)==' ')
{
k[p++]=t.substring(m,i);
m=i+1;
}
}
k[p++]=t.substring(m);
int a[]=new int[p];
for(i=0;i<p;i++)
{
a[i]=k[i].length();
}
for(i=0;i<p-1;i++)
{
for(m=0;m<p-1-i;m++)
{
if(a[m]>a[m+1])
{
du=a[m];
a[m]=a[m+1];
a[m+1]=du;
d=k[m];
k[m]=k[m+1];
k[m+1]=d;
}
}
}
t="";
for(i=0;i<p-1;i++)
{
t=t+k[i]+" ";
}
t=t+k[i];
t=t.toLowerCase();
char f=t.charAt(0);
f=Character.toUpperCase(f);
t=f+""+t.substring(1);
return t;
}
}