-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathReverseWordInString.java
64 lines (55 loc) · 1.91 KB
/
ReverseWordInString.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.geeksforgeeks.string;
import java.util.ArrayList;
import java.util.List;
public class ReverseWordInString {
public static void main(String[] args) {
reverseString("SAGAR IS LEARNING JAVA AND ANDRIOD");
reverseString("SAGAR IS A GOOD BOY");
reverseString("JAVA IS AWESOME");
reverseString("J");
}
/**
* 1) First Count the Spaces in the words
* 2) Run a loop for no of spaces time
* 3) Reverse respective words separated by space
* 4) Now after last space is done we will check that still there is any word left then call reverse for the last time
*
* @param str
*/
public static void reverseString(String str) {
List<Integer> spacesInString = new ArrayList<>();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
spacesInString.add(i);
}
}
char[] strInArr = str.toCharArray();
int lowIndex = 0;
for (Integer spaceIndex : spacesInString) {
reverse(strInArr, lowIndex, spaceIndex);
lowIndex = spaceIndex + 1;
}
if (lowIndex < strInArr.length) {
reverse(strInArr, lowIndex, strInArr.length);
}
System.out.println("Reverse of [" + str + "] :: " + String.valueOf(strInArr));
}
/**
* This method will reverse words in array ranging from lowIndex to highIndex
*
* @param strInArr
* @param lowIndex
* @param highIndex
*/
public static void reverse(char[] strInArr, int lowIndex, int highIndex) {
int lowCounter = lowIndex;
int highCounter = highIndex - 1;
for (int i = lowIndex; i < highIndex - 1; i++) {
char temp = strInArr[lowCounter];
strInArr[lowCounter] = strInArr[highCounter];
strInArr[highCounter] = temp;
highCounter--;
lowCounter++;
}
}
}