如何查找字符串中重复字符的最大值



我有一个字符串"aaabbb"

下面的程序返回最大重复值作为a。但是在这里,a和b都是最大重复字符。如何将a和b同时打印为最大重复字符

import java.util.HashMap;
import java.util.Map.Entry;
class MaxRepeatedCharactersInString 
{
public static void main(String[] args) 
{
String s = "acakabbba";
HashMap<Character, Integer> map = new HashMap<>();
char[] ch = s.toCharArray();
for(char c : ch)
{
if(map.containsKey(c))
{
map.put(c, map.get(c)+1);
}
else
{
map.put(c, 1);
}
}
int maxCount = 0;
char maxChar = ' ';
System.out.println("Maximum repeated character in String: ");
for(Entry<Character, Integer> entry : map.entrySet())
{
if(maxCount < entry.getValue())
{
maxCount = entry.getValue();
maxChar = entry.getKey();
}
}
System.out.println(maxChar+"="+maxCount);
}
}

我添加了一个额外的Stack和一个计数器来存储最多重复字符

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Stack;
class MaxRepeatedCharactersInString {
public static void main(String[] args) {
String s = "aa";
HashMap<Character, Integer> map = new HashMap<>();
char[] ch = s.toCharArray();
for (char c : ch) {
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
int maxCount = 0;
int noMax = 0;
Stack<Character> st = new Stack<>();
System.out.println("Maximum repeated characters in String: ");
for (Entry<Character, Integer> entry : map.entrySet()) {
if (maxCount < entry.getValue()) {
maxCount = entry.getValue();
noMax = 1;
st.push(entry.getKey());
} else if (maxCount == entry.getValue()) {
noMax++;
st.push(entry.getKey());
}
}
for (int i = 0; i < noMax; i++) {
System.out.println(st.pop() + "=" + maxCount);
}
}
}

相关内容

  • 没有找到相关文章

最新更新