将String aaaabbbbddd转换为a4b4d3
我正在努力开始练习面试问题,我遇到了这个问题:
将String aaaabbbbddd转换为a4b4d3
您基本上希望将现有字符串转换为每个唯一字符出现的字符串以及字符出现的次数。
这是我的解决方案,但我认为它可以被提炼成更优雅的东西:
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);
有没有人对解决方案有任何其他建议?
使用Map
代替。 尝试将新角色插入地图中; 如果它已经存在,则递增该特定字符的值。
例:
Map countMap = new HashMap<>(); if(!countMap.containsKey('a')) { countMap.put('a', 1); } else { countMap.put('a', countMap.get('a') + 1); }
要添加@ Makoto的精彩答案,在您的情况下,我会使用TreeMap
而不是HashMap
。 TreeMap
允许您按字母顺序打印。 我还添加了打印代码,以向您展示它的外观。 它完全可以运行。
import java.util.Map; import java.util.TreeMap; public class MapPractice { public static void main(String[] args) { Map map = new TreeMap<>(); String blah = "aaaabbbbddd"; for (int i = 0; i < blah.length(); i++) { char c = blah.charAt(i); if (!map.containsKey(c)) { map.put(c, 1); } else { map.put(c, (map.get(c) + 1)); } } for (Map.Entry entry: map.entrySet()) { System.out.print(entry.getKey() + "" + entry.getValue()); } } }
使用TreeMap
输出: a4b4d3
使用HashMap
输出: d3b4a4
我的版本
StringBuilder sb = new StringBuilder(); int count = 0; char last = s.charAt(0); for(char c : s.toCharArray()) { if (c == last) { count++; } else { sb.append(last).append(count); count = 0; last = c; } } if (count != 0) { sb.append(last).append(count); } System.out.println(sb);
这是我试过的代码。
我认为你不能要求比这更简单的代码。
String s = "aaaabbbbddd", modified = ""; int len = s.length(), i = 0, j = i + 1, count = 1; char[] c = s.toCharArray(); for (; i < len; i = j) { count = 1; for (; j < len; j++) if (c[i] == c[j]) count++; else { j++; break; } modified += c[i] + "" + count; } System.out.println(modified);
这是我的解决方案
public String countChars(String in){ LinkedHashMapMap map = new LinkedHashMap(); for(char c: in.toCharArray()){ Integer count = map.get(c); if(count==null){ count=0; } count++; map.put(c,count); } String out =""; for(Entry e : map.entrySet()){ out += e.getKey()+e.getValue(); } return out; }