Skip to content

Commit 452442c

Browse files
movehashtoend
1 parent 8b41533 commit 452442c

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/**
2+
* Moves all '#' characters to the end of the string.
3+
*
4+
* Time Complexity: O(n)
5+
* Space Complexity: O(1)
6+
*
7+
* Inspired by Move Zeroes problem:
8+
* https://leetcode.com/problems/move-zeroes/
9+
*
10+
* @author Shyam Chavda
11+
*/
12+
13+
package com.thealgorithms.twopointer;
14+
15+
public class MoveHash {
16+
17+
/** default constructor */
18+
public MoveHash() {}
19+
20+
/**
21+
* Place all hash to end of the String and return new String.
22+
*
23+
* @param s the input string.
24+
* @return the new string where hash place at the end.
25+
* returns null if the input string is null.
26+
*/
27+
28+
public static String movehashtoend(String s) {
29+
/** converts string into character array
30+
for example.,
31+
string = roman,
32+
character array = ['r','o','m','a','n']
33+
*/
34+
35+
char[] c = s.toCharArray();
36+
37+
/** return null if inputed string is null */
38+
if (s == null) {
39+
return "null";
40+
}
41+
42+
/** j works like a tracker the hash position */
43+
int j = 0;
44+
45+
/** i traverse whole character array.
46+
* if character is non-hash then easily swap with tracker(j) position
47+
*
48+
* for example.,
49+
* input string = a#bc;
50+
* at first traverse current non-hash character(a) swap with j position.
51+
*
52+
* string becomes #abc.
53+
* this continuos untill i reaches to end of string.
54+
*/
55+
56+
for (int i=0; i<c.length; i++) {
57+
if (c[i] != '#') {
58+
swap(i, j, c);
59+
j++;
60+
}
61+
}
62+
63+
/** converts the character array to String at a time and returns. */
64+
return new String(c);
65+
}
66+
67+
/** simple swapping logic with third variable. */
68+
public static void swap(int a, int b, char[] c) {
69+
char tmp = c[a];
70+
c[a] = c[b];
71+
c[b] = tmp;
72+
}
73+
74+
public static void main(String[] args) {
75+
/** input part. */
76+
String input = "h#e#l###l#o";
77+
78+
/** output catches through the function. */
79+
String output = movehashtoend(input);
80+
81+
/** display appropriate output. */
82+
System.out.println(output);
83+
}
84+
}

0 commit comments

Comments
 (0)