题解 | #压缩牛群编号#
压缩牛群编号
https://www.nowcoder.com/practice/db9dd240e5f54b6d8eeadfbd9b7f865f
考察双指针算法的应用。具体代码细节如下所示,使用Java代码。
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param chars char字符型一维数组
* @return char字符型一维数组
*/
public char[] compress (char[] chars) {
// write code here
int n = chars.length, write = 0;
for(int i =0;i<n;){
int j = i;
while(j<n && chars[i] == chars[j]){
++j;
}
chars[write++] = chars[i];
if(j - i >1){
String tmp = Integer.toString(j-i);
for(int k = 0;k<tmp.length();++k){
chars[write++] = tmp.charAt(k);
}
}
i = j;
}
char[] res = new char[write];
for(int i=0; i<write; i++){
res[i] = chars[i];
}
return res;
}
}

查看1道真题和解析