题解 | #压缩字符串(一)#
压缩字符串(一)
https://www.nowcoder.com/practice/c43a0d72d29941c1b65c857d8ac9047e
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param param string字符串 * @return string字符串 */ public String compressString (String param) { // write code here if(param == null || param.equals("")) { return ""; } StringBuffer sb = new StringBuffer(); int i = 0; int j = 1; while (j < param.length()) { if (param.charAt(i) == param.charAt(j)) { j++; continue; } else { sb.append(param.charAt(i)); if (j - i > 1) { sb.append(j - i); } i = j; j++; } } sb.append(param.charAt(param.length() - 1)); if (j - i > 1) { sb.append(j - i); } return sb.toString(); } }