-
Notifications
You must be signed in to change notification settings - Fork 21k
Expand file tree
/
Copy pathMoveHashToEnd.java
More file actions
56 lines (49 loc) · 1.49 KB
/
MoveHashToEnd.java
File metadata and controls
56 lines (49 loc) · 1.49 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
package com.thealgorithms.strings;
/**
* Moves all '#' characters to the end of the given string while preserving
* the order of the other characters.
*
* Example:
* Input : "h#e#l#llo"
* Output : "helllo###"
*
* The algorithm works by iterating through the string and collecting
* all non-# characters first, then filling the remaining positions
* with '#'.
*
* Time Complexity: O(n)
* Space Complexity: O(n)
*
* @see <a href="https://www.geeksforgeeks.org/move-special-char-end-string-maintain-order-alphabets/">Move all special characters to end - GeeksForGeeks</a>
*/
public final class MoveHashToEnd {
/**
* Private constructor to prevent instantiation of utility class.
*/
private MoveHashToEnd() {
}
/**
* Moves all '#' characters in the input string to the end.
*
* @param str the input string containing characters and '#'
* @return a new string with all '#' characters moved to the end
*/
public static String moveHashToEnd(String str) {
if (str == null || str.isEmpty()) {
return str;
}
char[] arr = str.toCharArray();
int insertPos = 0;
// Place all non-# characters at the beginning
for (char ch : arr) {
if (ch != '#') {
arr[insertPos++] = ch;
}
}
// Fill remaining positions with '#'
while (insertPos < arr.length) {
arr[insertPos++] = '#';
}
return new String(arr);
}
}