tasks a-s
This commit is contained in:
parent
47bf37c096
commit
b83f433714
12433 changed files with 156208 additions and 123 deletions
38
Task/Run-length-encoding/Java/run-length-encoding-1.java
Normal file
38
Task/Run-length-encoding/Java/run-length-encoding-1.java
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
public class RunLengthEncoding {
|
||||
|
||||
public static String encode(String source) {
|
||||
StringBuffer dest = new StringBuffer();
|
||||
for (int i = 0; i < source.length(); i++) {
|
||||
int runLength = 1;
|
||||
while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
|
||||
runLength++;
|
||||
i++;
|
||||
}
|
||||
dest.append(runLength);
|
||||
dest.append(source.charAt(i));
|
||||
}
|
||||
return dest.toString();
|
||||
}
|
||||
|
||||
public static String decode(String source) {
|
||||
StringBuffer dest = new StringBuffer();
|
||||
Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z]");
|
||||
Matcher matcher = pattern.matcher(source);
|
||||
while (matcher.find()) {
|
||||
int number = Integer.parseInt(matcher.group());
|
||||
matcher.find();
|
||||
while (number-- != 0) {
|
||||
dest.append(matcher.group());
|
||||
}
|
||||
}
|
||||
return dest.toString();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String example = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
|
||||
System.out.println(encode(example));
|
||||
System.out.println(decode("1W1B1W1B1W1B1W1B1W1B1W1B1W1B"));
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue