题解 | #压缩牛群编号#
压缩牛群编号
https://www.nowcoder.com/practice/db9dd240e5f54b6d8eeadfbd9b7f865f
题目考察的知识点是:
字符串的遍历。
题目解答方法的文字分析:
遍历chars数组,记录相同元素的个数放入map集合中,不相同,则将count转为字符串,然后插入到字符串中即可。
本题解析所用的编程语言:
java语言。
完整且正确的编程代码:
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param chars char字符型一维数组
* @return char字符型一维数组
*/
public char[] compress (char[] chars) {
// write code here
String res = "";
int n = chars.length;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(chars[i], map.getOrDefault(chars[i], 0) + 1);
}
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
res += entry.getKey();
if (entry.getValue() > 1)
res += entry.getValue();
}
return res.toCharArray();
}
}
#题解#