-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathRearrangeSpaces.java
78 lines (76 loc) · 2.58 KB
/
RearrangeSpaces.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
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
/*https://leetcode.com/problems/rearrange-spaces-between-words/*/
class Solution {
public String reorderSpaces(String text) {
int actualLength = text.length();
int alphaLength = 0;
String[] tokens = text.trim().split(" +");
for (String token : tokens)
alphaLength += token.length();
int totalSpaceLength = actualLength-alphaLength;
int spaces = tokens.length-1;
int rem = 0;
StringBuffer result = new StringBuffer("");
if (spaces != 0)
{
int spaceLength = totalSpaceLength/spaces;
rem = totalSpaceLength-(spaces*spaceLength);
for (int i = 0; i < tokens.length-1; ++i)
{
result.append(tokens[i]);
for (int j = 0; j < spaceLength; ++j)
result.append(" ");
}
}
else
rem = totalSpaceLength;
result.append(tokens[tokens.length-1]);
for (int j = 0; j < rem; ++j)
result.append(" ");
return result.toString();
}
}
class Solution {
public String reorderSpaces(String text) {
int actualLength = text.length();
int totalSpaceLength = 0, words = 0;
for (int i = 0; i < actualLength; ++i)
{
if (text.charAt(i) == ' ')
++totalSpaceLength;
if (text.charAt(i) != ' ' && (i == actualLength-1 || text.charAt(i+1) == ' '))
++words;
}
if (words == 1)
{
StringBuffer newText = new StringBuffer(text.trim());
while (totalSpaceLength-- > 0)
newText.append(' ');
return newText.toString();
}
int spaces = words-1;
int rem = 0;
StringBuffer result = new StringBuffer("");
int i = 0;
while (text.charAt(i) == ' ') ++i;
if (spaces != 0)
{
int spaceLength = totalSpaceLength/spaces;
rem = totalSpaceLength-(spaces*spaceLength);
for (; i < actualLength; ++i)
{
while (i < actualLength && text.charAt(i) != ' ')
result.append(text.charAt(i++));
while (i < actualLength && text.charAt(i) == ' ') ++i;
--i;
for (int j = 0; j < spaceLength; ++j)
result.append(" ");
}
}
else
rem = totalSpaceLength;
result = new StringBuffer(result.toString().trim());
for (int j = 0; j < rem; ++j)
result.append(" ");
return result.toString();
}
}