字符串压缩
public class StrCutDown { /** * 字符串压缩范围[a-zA-Z] 输入如:aaabbbccca =>> a3b3c3a1 * 压缩后的字符串要小于原字符串,否则返回原字符串 * @param args */ public static void main(String[] args) { String str = "aaabbbccca"; System.out.println(strZip(str)); } public static String strZip(String source) { if (StringUtils.isBlank(source)) { return source; } char[] c = source.toCharArray(); if (c.length == 1) { return source; } int i = 0; int j = 1; StringBuilder stringBuilder = new StringBuilder(); int index = 1; while (i < c.length && j < c.length) { if (c[i] == c[j]) { index++; j++; } else { stringBuilder.append(c[i]).append(index); i = j; j = i + 1; index = 1; } if (j >= c.length) { stringBuilder.append(c[i]).append(index); } } return source.length() <= stringBuilder.length() ? source : stringBuilder.toString(); } }
缘于生活,而归于工作。本人所书,而意于分享。
如有转载,请注明出处!
--活出自己范儿