利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串“aabcccccaaa”经压缩会变成“a2b1c5a3”。若压缩后的字符串没有变短,则返回原先的字符串。 给定一个string iniString为待压缩的串(长度小于等于10000),保证串内字符均由大小写英文字母组成,返回一个string,为所求的压缩后或未变化的串。 测试样例 “aabcccccaaa” 返回:”a2b1c5a3” “welcometonowcoderrrrr” 返回:”welcometonowcoderrrrr”
解题思路:定义一个StringBuilder,遍历字符串,停机是否有重复出现的字符,有的话则累加,每个字符后面跟上对应字符的个数,与原字符串长度进行比较,短则采用,否则,不采用。
import java.util.*; public class Zipper { public String zipString(String iniString) { // write code here int low = 0 , high = 0 ; int len = iniString.length(); StringBuilder sb = new StringBuilder(); char c = ' '; int count = 0; while(low < len){ high = low; c = iniString.charAt(low); while((high < len)&&(iniString.charAt(high) == c)){ high ++; } count = high - low ; sb.append(c); sb.append(count); low = high; } return (sb.toString().length() < len)?sb.toString():iniString; } } 转自:https://blog.csdn.net/qq_29606255/article/details/78477517