Last active
December 13, 2015 18:18
-
-
Save kyktommy/4953928 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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