Created
June 17, 2014 01:48
-
-
Save k1xme/30d8ea8624913bf7c18f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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