题解 | #压缩牛群编号#
压缩牛群编号
https://www.nowcoder.com/practice/db9dd240e5f54b6d8eeadfbd9b7f865f
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param chars char字符型一维数组 * @return char字符型一维数组 */ public char[] compress (char[] chars) { // write code here char cur = chars[0]; int times = 1, index = 1; for (int i = 1; i < chars.length; i++) { if (chars[i] == cur) { times++; } else { if (times > 1) { char[] arr = String.valueOf(times).toCharArray(); for (char c : arr) { chars[index++] = c; } } times = 1; cur = chars[i]; chars[index++] = cur; } } if (times > 1) { char[] arr = String.valueOf(times).toCharArray(); for (char c : arr) { chars[index++] = c; } } return Arrays.copyOfRange(chars, 0, index); } }