Advertisement
Guest User

Untitled

a guest
Dec 21st, 2014
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. /*
  2. * CC150 1.5 Compress String
  3. * @author: Scarlett Chen
  4. * @time: 12/20/2014 Sat 9:57 PM
  5. * 时空复杂度都是o(n)?如果n是字符串里的字符数的话
  6. * 思路是:
  7. * 遍历每个字符,是否与前一个一样,一样就把count+1.不一样就把该字符和它的count放到压缩后的字符串内。
  8. * 当newString长度大于originalString时,继续对比就没有意义了,直接返回原来的字符串。
  9. *
  10. *
  11. * Implement a method to perform basic string compression using the counts of repeated characters.
  12. * For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not
  13. * become smaller than the original string, your method should return the original string.
  14. */
  15. public class CompressString {
  16. public String compress(String s) {
  17. int len = s.length();
  18. if (len<=2) return s;
  19. char[] ch = s.toCharArray();
  20. StringBuilder newString = new StringBuilder();
  21. char currentChar=' ';
  22. int currentCount = 0;
  23. for (int i=0; i<len; i++) {
  24. if (i>0 && ch[i]==ch[i-1]) {
  25. currentCount++;
  26. }
  27. else {
  28. if (i>0) {
  29. newString.append(currentChar);
  30. newString.append(currentCount);
  31. if (newString.length()>len) return s;
  32. }
  33. currentChar = ch[i];
  34. currentCount = 1;
  35.  
  36. }
  37. }
  38. if (newString.length()>= len) return s;
  39. else return newString.toString();
  40. }
  41.  
  42. public static void main(String[] args) {
  43. // TODO Auto-generated method stub
  44. CompressString cs = new CompressString();
  45. String s = "aabcccccaaa";
  46. System.out.println(s+"--->"+cs.compress(s));
  47. s = "aa";
  48. System.out.println(s+"--->"+cs.compress(s));
  49. s = "#";
  50. System.out.println(s+"--->"+cs.compress(s));
  51. s = "Jiali Chen";
  52. System.out.println(s+"--->"+cs.compress(s));
  53.  
  54. }
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement