-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSentenceRev.java
More file actions
52 lines (42 loc) · 1.04 KB
/
Copy pathSentenceRev.java
File metadata and controls
52 lines (42 loc) · 1.04 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
45
46
47
48
49
50
51
52
import java.util.Arrays;
public class SentenceRev
{
public static void main(String[] args)
{
System.out.println("\""+reverseWords(" 1")+"\"");
System.out.println("\""+reverseWords("the blue sky there")+"\"");
System.out.println("\""+reverseWords(" a ")+"\"");
}
public static String reverseWords(String s) {
// remove extra white spaces
s = s.trim().replaceAll(" +", " ");
// split by spaces
String[] exp = s.split(" ");
// System.out.println(Arrays.toString(exp));
// 1 item + space case
if(exp.length == 2)
{
if(exp[0].equals(""))
{
return exp[1];
}
}
// flip words
for(int i = 0; i < exp.length/2; i++)
{
String temp = exp[i];
exp[i] = exp[exp.length - 1- i];
exp[exp.length - 1 - i] = temp;
}
String ans = "";
// concat together
for(int i = 0; i < exp.length - 1; i++)
ans += exp[i] + " ";
// see if the last item to be added is a space
if(exp.length != 0 && !(exp[exp.length - 1].equals(" ")))
{
ans += exp[exp.length - 1];
}
return ans;
}
}