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