-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathReverseword.java
45 lines (41 loc) · 1.14 KB
/
Reverseword.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
/*
* Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
* Source: https://github.com/surajr/CodingInterview/
* Licence: MIT
*
* Example 1:
* Input: "Let's take LeetCode contest"
* Output: "s'teL ekat edoCteeL tsetnoc"
*/
public class Reverseword {
public String reverseWords(String s)
{
char [] str = s.toCharArray();
int i = 0;
for(int j=0; j < str.length; j++)
{
if(str[j] == ' ')
{
reverse(str, i, j-1);
i = j+1;
}
}
reverse(str, i, str.length-1);
return new String(str);
}
public void reverse(char [] str, int l, int r)
{
while( l < r )
{
char temp = str[l];
str[l] = str[r];
str[r] = temp;
l++; r--;
}
}
public static void main(String[] args) {
Reverseword rw = new Reverseword();
System.out.println("Input: " + args[0]);
System.out.println("Output: " + rw.reverseWords(args[0]));
}
}