Skip to content

Medium challenges #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Aug 17, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Run Length
  • Loading branch information
ardallie committed Aug 17, 2021
commit 5dbf768519b2279ba89a056de4271dd2dc935411
50 changes: 50 additions & 0 deletions src/medium/RunLength.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package medium;

/**
* Have the function RunLength(str) take the str parameter being passed
* and return a compressed version of the string using the Run-length encoding algorithm.
* ---
* This algorithm works by taking the occurrence of each repeating character
* and outputting that number along with a single character of the repeating sequence.
* ---
* For example: "wwwggopp" would return 3w2g1o2p.
* The string will not contain any numbers, punctuation, or symbols.
*/
public class RunLength {

/**
* Run Length function.
*
* @param str input string
* @return a compressed version of the string
*/
private static String runLength(String str) {
StringBuilder output = new StringBuilder();
int count = 0;
char prev = str.charAt(0);
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == prev) {
count++;
} else {
output.append(count).append(prev);
count = 1;
prev = str.charAt(i);
}
}
output.append(count).append(prev);
return output.toString();
}

/**
* Entry point.
*
* @param args command line arguments
*/
public static void main(String[] args) {
var result1 = runLength("ultrarevolutionaries");
System.out.println(result1);
var result2 = runLength("underworld");
System.out.println(result2);
}

}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy