Skip to content

Instantly share code, notes, and snippets.

@kyktommy
Last active December 13, 2015 18:18
Show Gist options
  • Save kyktommy/4953928 to your computer and use it in GitHub Desktop.
Save kyktommy/4953928 to your computer and use it in GitHub Desktop.
public String compress(String str) {
String result = "";
List<String> nodes = new ArrayList<String>();
Pattern pattern = Pattern.compile("(.)\\1{1,}");
Matcher m = pattern.matcher(str);
int offset = 0;
while( m.find() ) {
int start = m.start();
int end = m.end();
// Ouput non repeat
if( offset < start ) {
nodes.add(str.substring(offset, start));
}
nodes.add(str.substring(start, end));
offset = end;
}
if( offset == 0 ) {
nodes.add(str);
} else if( offset != str.length() ) {
nodes.add(str.substring(offset, str.length()));
}
for( String s : nodes ) {
if(s.isEmpty()) continue;
if(s.length() == 1 || s.charAt(0) != s.charAt(1)) {
result += "n" + s.length() + s;
}
else {
result += "r" + s.length() + s.charAt(0);
}
};
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment