Skip to content

Commit c45b7ea

Browse files
Create Question1.java
1 parent f5a7ca7 commit c45b7ea

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

important-questions/Question1.java

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.javamultiplex.interview.ds;
2+
3+
import java.util.Scanner;
4+
5+
/*
6+
*
7+
* Input - I Love My India
8+
* Output - India My Love I
9+
*
10+
*/
11+
public class Question1 {
12+
13+
public static void main(String[] args) {
14+
15+
Scanner input = new Scanner(System.in);
16+
System.out.println("Enter String : ");
17+
String sentence = input.nextLine();
18+
String output = reverseString(sentence);
19+
System.out.println(output);
20+
input.close();
21+
}
22+
23+
private static String reverseString(String sentence) {
24+
25+
StringBuffer stringBuffer = new StringBuffer(sentence);
26+
int length = stringBuffer.length();
27+
int start = 0, end = 0;
28+
for (int i = 0; i < length; i++) {
29+
30+
if (stringBuffer.charAt(i) == ' ' || i == stringBuffer.length() - 1) {
31+
end = i;
32+
if (i != stringBuffer.length() - 1) {
33+
end--;
34+
}
35+
swap(stringBuffer, start, end);
36+
start = i + 1;
37+
}
38+
}
39+
swap(stringBuffer, 0, length - 1);
40+
return stringBuffer.toString();
41+
}
42+
43+
private static void swap(StringBuffer stringBuffer, int start, int end) {
44+
45+
char temp = '\u0000';
46+
while (start < end) {
47+
temp = stringBuffer.charAt(start);
48+
stringBuffer.setCharAt(start, stringBuffer.charAt(end));
49+
stringBuffer.setCharAt(end, temp);
50+
start++;
51+
end--;
52+
}
53+
54+
}
55+
56+
}

0 commit comments

Comments
 (0)