将String aaaabbbbddd转换为a4b4d3 [英] Turn String aaaabbbbddd into a4b4d3
问题描述
我正在尝试练习面试问题,我遇到了这个问题:
I'm trying to get a head start on practicing interview questions and I came across this one:
将字符串aaaabbbbddd变成a4b4d3
Turn String aaaabbbbddd into a4b4d3
您基本上希望将现有字符串转换为每个唯一字符出现的字符串以及字符出现的次数。
You would basically want to convert the existing string into a string with each unique character occurrence and the number of times the character occurs.
这是我的解决方案,但我认为它可以被提炼成更优雅的东西:
This is my solution but I think it could be refined into something more elegant:
String s = "aaaabbbbddd";
String modified = "";
int len = s.length();
char[] c = s.toCharArray();
int count = 0;
for (int i = 0; i < len; i++) {
count = 1;
for (int j = i + 1; j < len; j++) {
if (c[i] == ' ') {
break;
}
if (c[i] == c[j]) {
count++;
c[j] = ' ';
}
}
if (c[i] != ' ') {
modified += c[i] + "" + count;
}
}
System.out.println(modified);
有没有人对解决方案有任何其他建议?
Does anyone have any other suggestions for a solution?
推荐答案
转而使用 Map< Character,Integer>
。尝试将新角色插入地图中;如果它已经存在,则增加该特定字符的值。
Employ a Map<Character, Integer>
instead. Attempt to insert the new character into the map; if it already exists, then increment the value for that particular character.
示例:
Map<Character, Integer> countMap = new HashMap<>();
if(!countMap.containsKey('a')) {
countMap.put('a', 1);
} else {
countMap.put('a', countMap.get('a') + 1);
}
这篇关于将String aaaabbbbddd转换为a4b4d3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!