-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreverse_words.java
More file actions
71 lines (61 loc) · 1.83 KB
/
reverse_words.java
File metadata and controls
71 lines (61 loc) · 1.83 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.ub.codeeval;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class reverse_words {
//TODO : reverse words in place
//not use extra space so used stringbuffer container
String doSubReverse(StringBuffer str) {
int len = str.length();
for(int i = 0,j= len -1;i<j;i++,j--) { //don't do j<len use i<j terminating condition same for palindrome
char temp = str.charAt(j);
str.setCharAt(j,str.charAt(i));
str.setCharAt(i, temp);
}
return str.toString();
}
private void revString(StringBuffer str) {
//reverse string
String t = doSubReverse(str);
//reverse words within string
String arr[] = t.split(" ");
int len = arr.length;
for(int i = 0;i<len - 1;i++) {
System.out.print(doSubReverse(new StringBuffer(arr[i])) + " ");
}
System.out.print(doSubReverse(new StringBuffer(arr[len-1])));
}
private void reverseString (String str) {
String tokens[] = str.split(" ");
int len = tokens.length;
for (int i = len -1;i >=0 ;i--) {
if(i != 0)
System.out.print(tokens[i] + " ");
else
System.out.print(tokens[i]);
}
}
public static void main(String args[]) {
reverse_words rev = new reverse_words();
File file = new File(args[0]);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
// String line;
String line;
while((line = br.readLine()) != null) {
// rev.reverseString(line);
StringBuffer str = new StringBuffer(line);
rev.revString(str);
System.out.print("\n");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}