forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoveExtraSpaces.java
65 lines (54 loc) · 2.04 KB
/
RemoveExtraSpaces.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
65
package com.rampatra.strings;
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 10/25/15
* @time: 9:44 PM
*/
public class RemoveExtraSpaces {
/**
* Removes extra spaces in string {@param s} without creating a
* extra variable to hold the result, in O(n) time complexity.
*
* @param s
* @return
*/
public static String removeExtraSpaces(String s) {
char[] c = s.toCharArray();
int j = c.length;
for (int i = 1; i < c.length; i++) {
// check for two or more consecutive spaces
if (c[i] == ' ' && c[i - 1] == ' ') {
// if extra spaces encountered for the 1st time
if (j == c.length) j = i;
// skip all extra spaces
while (i < c.length && c[i] == ' ') {
i++;
}
// if reached end of string then stop
if (i == c.length) break;
}
// copy characters occurring after extra spaces to their appropriate positions
while (i < c.length && j < c.length) {
// stop when you encounter extra spaces again
if (c[i] == ' ' && c[i - 1] == ' ') break;
c[j] = c[i];
i++;
j++;
}
}
return String.valueOf(Arrays.copyOf(c, j));
}
public static void main(String[] args) {
System.out.println(removeExtraSpaces("ram swaroop is a good boy."));
System.out.println(removeExtraSpaces("ram swaroop is a good boy."));
System.out.println(removeExtraSpaces(" ram swaroop is a good boy."));
System.out.println(removeExtraSpaces("ram swaroop is a good boy ."));
System.out.println(removeExtraSpaces(" ram swaroop is a good boy ."));
System.out.println(removeExtraSpaces(" "));
System.out.println(removeExtraSpaces(""));
System.out.println(removeExtraSpaces(" "));
}
}