-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathreverseWords1.java
51 lines (42 loc) · 1.13 KB
/
reverseWords1.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
public class Solution {
public String reverseWords(String s) {
if (s.length() == 0)
return null;
char [] a = s.toCharArray();
int n = a.length;
reverse(a, 0, n-1);
reverseWords(a, n);
return cleanSpaces(a, n);
}
public void reverse(char [] a, int i, int j)
{
while(i<j)
{
char temp = a[i];
a[i++] = a[j];
a[j--] = temp;
}
}
public void reverseWords(char [] a, int n)
{
int i=0, j=0;
while(i<n)
{
while(i < j || i < n && a[i] == ' ') i++;
while(j < i || j < n && a[j] != ' ') j++;
reverse(a, i, j-1);
}
}
public String cleanSpaces(char [] a, int n)
{
int i=0, j=0;
while(j < n)
{
while (j < n && a[j] == ' ') j++;
while (j < n && a[j] != ' ') a[i++] = a[j++];
while (j < n && a[j] == ' ') j++;
if (j < n) a[i++] = ' ';
}
return new String(a).substring(0, i);
}
}