我试图通过采用带有重复字符的输入字符串来压缩字符串。 例如, 输入:aabbbc --->输出:a2b3c1
我已经使用hashmap解决了这个问题。与上面相同的示例,我得到的输出为:-a1a2b1b2b3c1
public class NewClass {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
Map<Character,Integer> a= new HashMap<>();
String st=s.next();
char c[]=st.toCharArray();
for (char x:c){
if(a.containsKey(x)){
a.put(x,a.get(x)+1);
}
else{
a.put(x, 1);
}
System.out.print(x+""+a.get(x));
}
}
}
有人可以告诉我如何只打印一次具有最大值的密钥,或者逻辑上有什么问题吗?
答案 0 :(得分:2)
遍历所有条目并跟踪最大值另外,请考虑将地图重命名为比'a'更具有描述性的内容
int maxFreq = 0;
Character maxFreqChar = null;
for ( Map.Entry<Character, Integer> entry : a.entrySet() ) {
int value = entry.getValue();
if (value > maxFreq) {
maxFreq = value;
maxFreqChar = entry.getKey();
}
}
System.out.println(maxFreqChar);
答案 1 :(得分:0)
尝试一下
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
Map<Character,Integer> a= new HashMap<>();
String st=s.next();
char[] c = st.toCharArray();
for (Character x:c){
if(a.putIfAbsent(x, 1) != null) {
a.put(x, a.get(x) + 1);
}
}
String result = a.entrySet().stream()
.map(entry -> entry.getKey() + "" + entry.getValue())
.collect(Collectors.joining());
System.out.println(result);
}
答案 2 :(得分:0)
一个简单的逐步解决方案是:
1-在for循环中通过“字符”更改“字符”
public class NewClass {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
Map<Character,Integer> a= new HashMap<>();
String st=s.next();
char c[]=st.toCharArray();
for (Character x:c){
if(a.containsKey(x)){
a.put(x,a.get(x)+1);
}
else{
a.put(x, 1);
}
System.out.print(x+""+a.get(x));
}
}
}
2-然后,删除“ System.out.println”,并在单独的循环中进行操作:
public class NewClass {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
Map<Character,Integer> a= new HashMap<>();
String st=s.next();
char c[]=st.toCharArray();
for (Character x:c){
if(a.containsKey(x)){
a.put(x,a.get(x)+1);
}
else{
a.put(x, 1);
}
// System.out.print(x+""+a.get(x));
}
// print result here
for (Character k:a.keySet()){
System.out.print(k+""+a.get(k));
}
}
}