Skip to content

Instantly share code, notes, and snippets.

@k1xme
Created June 17, 2014 01:48
Show Gist options
  • Save k1xme/30d8ea8624913bf7c18f to your computer and use it in GitHub Desktop.
Save k1xme/30d8ea8624913bf7c18f to your computer and use it in GitHub Desktop.
class Solution{
/*
* Space complexity: O(n); Time complexity: O(n).
*/
public static String compression(String str){
if(str == null || str.isEmpty()) return str;
char[] chars = str.toCharArray();
StringBuffer result = new StringBuffer();
int count = 1; // Count the first char.
for(int i = 0; i<chars.length - 1; i++){
if(chars[i] == chars[i+1]) count++;
if(chars[i] != chars[i+1] || i==chars.length - 2){ // When the next char is different or the end, append the char and its count to result.
result.append(chars[i]);
result.append(count);
count = 1; // Start to count the next different char.
}
}
return result.length() < str.length()? result.toString() : str;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment