Skip to content

Commit 5dbf768

Browse files
committed
Run Length
1 parent 5e61a31 commit 5dbf768

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

src/medium/RunLength.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package medium;
2+
3+
/**
4+
* Have the function RunLength(str) take the str parameter being passed
5+
* and return a compressed version of the string using the Run-length encoding algorithm.
6+
* ---
7+
* This algorithm works by taking the occurrence of each repeating character
8+
* and outputting that number along with a single character of the repeating sequence.
9+
* ---
10+
* For example: "wwwggopp" would return 3w2g1o2p.
11+
* The string will not contain any numbers, punctuation, or symbols.
12+
*/
13+
public class RunLength {
14+
15+
/**
16+
* Run Length function.
17+
*
18+
* @param str input string
19+
* @return a compressed version of the string
20+
*/
21+
private static String runLength(String str) {
22+
StringBuilder output = new StringBuilder();
23+
int count = 0;
24+
char prev = str.charAt(0);
25+
for (int i = 0; i < str.length(); i++) {
26+
if (str.charAt(i) == prev) {
27+
count++;
28+
} else {
29+
output.append(count).append(prev);
30+
count = 1;
31+
prev = str.charAt(i);
32+
}
33+
}
34+
output.append(count).append(prev);
35+
return output.toString();
36+
}
37+
38+
/**
39+
* Entry point.
40+
*
41+
* @param args command line arguments
42+
*/
43+
public static void main(String[] args) {
44+
var result1 = runLength("ultrarevolutionaries");
45+
System.out.println(result1);
46+
var result2 = runLength("underworld");
47+
System.out.println(result2);
48+
}
49+
50+
}

0 commit comments

Comments
 (0)