Skip to content

Commit 007f4fa

Browse files
committed
Create reverseWordsInSentenseInConstantMemory
1 parent 4f5d514 commit 007f4fa

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
2+
/*
3+
* Question: Inplace reverse a sentence
4+
5+
You given a sentence of english words and spaces between them.
6+
Nothing crazy:
7+
1) no double spaces
8+
2) no empty words
9+
3) no spaces at the ends of a sentence
10+
11+
12+
void inplace_reverse(char* arr, int length) {
13+
// your solution
14+
}
15+
Example:
16+
input "I wish you a merry Christmas"
17+
output "Christmas merry a you wish I"
18+
19+
Constrains: O(1) additional memory
20+
21+
22+
23+
Source: http://www.careercup.com/question?id=5717567253512192
24+
25+
Algorithm: 1. Reverse the words in the sentence
26+
2. Reverse the sentence
27+
28+
Example:
29+
Input: I wish you a merry Christmas
30+
step 1 . I hisw uoy a yrrem samtsirhC
31+
step 2 . Christmas merry a you wish I
32+
33+
*/
34+
35+
36+
37+
package reverseWordsInSentenseInConstantMemory;
38+
39+
import java.util.Scanner;
40+
41+
public class UsingReverseWordsFunction {
42+
public static void main(String[] args) {
43+
Scanner in = new Scanner(System.in);
44+
try{
45+
System.out.println("Enter the sentence whose words needs to be reversed");
46+
char[] s = in.nextLine().toCharArray();
47+
s=reverseSentence(s);
48+
System.out.println(String.valueOf(s));
49+
50+
}finally{
51+
in.close();
52+
}
53+
}
54+
/* Preconditions of the input string given in the question:
55+
1) no double spaces
56+
2) no empty words
57+
3) no spaces at the ends of a sentence
58+
*/
59+
public static void reverseWord(char[] s,int start, int end){
60+
for(;start<end;start++,end--){
61+
// Swap start and end characters In Place
62+
s[start] = (char)(s[start]^s[end]);
63+
s[end] = (char)(s[start]^s[end]);
64+
s[start] = (char)(s[start]^s[end]);
65+
}
66+
}
67+
public static char[] reverseSentence(char[] s){
68+
int start = 0;
69+
int end = 0;
70+
for(int i=0;i<s.length;i++){
71+
72+
if(s[i]==' '){ // either when we get empty space
73+
end=i-1;
74+
reverseWord(s, start, end);
75+
start=i+1;
76+
}
77+
if(i==(s.length-1)){ // If we reach the end of the string
78+
end=i;
79+
reverseWord(s, start, end);
80+
}
81+
}
82+
reverseWord(s, 0, s.length-1);
83+
return s;
84+
}
85+
}
86+
/*
87+
* Analysis:
88+
* Time Complexity = O(n) where n = length of the string
89+
* Space Complexity = O(1)
90+
*/

0 commit comments

Comments
 (0)