Last active
August 29, 2015 14:03
-
-
Save WOLOHAHA/645a705481e17a494367 to your computer and use it in GitHub Desktop.
Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string.
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 class Main { | |
/** | |
* @Runtime & spaces ||runtime: O(n) ||space: O(n) | |
*/ | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
Main so = new Main(); | |
String s = "a"; | |
System.out.println(so.compress(s)); | |
} | |
public String compress(String s) { | |
if (s == null || s.length() == 0) | |
return s; | |
//use StringBuffer other than String to save time and space | |
StringBuffer result = new StringBuffer(); | |
char last = s.charAt(0); | |
int count = 1; | |
for (int i = 1; i < s.length(); i++) { | |
if (s.charAt(i) == last) { | |
count++; | |
} else { | |
result.append(last); | |
result.append(count); | |
last = s.charAt(i); | |
count = 1; | |
} | |
} | |
result.append(last); | |
result.append(count); | |
if (result.length() >= s.length()) | |
return s; | |
return result.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment