我需要从jTextFrame中取一个字符串,然后将其排序为出现顺序,然后将其打印出来。例如。 babablackbike返回:bbbbaaakkceil
String word = (String)jTextField1.getText();
String indexes = "abcdefghijklmnopqrstuvwxyz";
int[] count = new int[indexes.length()];
for (int i = 0; i < word.length(); i++)
{
int index = indexes.indexOf(word.charAt(i));
if (index < 0)
continue;
count[index]++;
}
for (int j = 0; j < count.length; j++)
{
if (count[j] < 1)
continue;
char[] indiv = indexes.toCharArray();
for (int p = 0; p < count[j];p++)
{
jTextArea1.append(""+indiv[j]);
System.out.println(indiv[(j)] +"="+ count[j] + p);
}
}
答案 0 :(得分:0)
我认为,最好的解决方案是创建像这样的HashMap
Map<Character, Integer> quantity = new HashMap<Character, Integer>();
然后,你可以这样做一个循环:
for (int i = 0; i < str.length() - 1; i++) {
char c = str.charAt(i);
// increment value of c in quantity map
}
之后,您可以按值对其进行排序并轻松打印。
答案 1 :(得分:0)
首先需要输入输入中每个字符的计数:
final String in = "babablackbike";
final Map<Character, Integer> counts = new HashMap<>();
final List<Character> inList = new ArrayList<>();
for (final char c : in.toCharArray()) {
Integer count = counts.get(c);
if (count == null) {
counts.put(c, 1);
} else {
counts.put(c, count + 1);
}
inList.add(c);
}
由于Java在char[]
与Character[]
之间有点奇怪 - 由于泛型无法使用基元,因此无法使用自定义比较器对基元进行排序 - 我还构建了List<Character>
在同一时间。
现在我们只需要使用自定义List<Character>
和Comparator
中的信息对Map counts
进行排序:
Collections.sort(inList, new Comparator<Character>() {
@Override
public int compare(final Character o1, final Character o2) {
int c = counts.get(o1).compareTo(counts.get(o2));
if (c != 0) {
return -c;
}
return o1.compareTo(o2);
}
});
首先,我们按输入中的字符计数(反向顺序)排序,然后按字符本身排序。
现在我们只需要将List
构建回String
:
final StringBuilder outBuilder = new StringBuilder();
for (final Character c : inList) {
outBuilder.append(c);
}
System.out.println(outBuilder.toString());
输出:
bbbbaaakkceil
答案 2 :(得分:0)
以下是一般算法:
这是一个编码示例:
public void Print(String string)
{
HashMap<Character,Integer> hashMap = new HashMap<Character,Integer>();
TreeMap<Character,Integer> treeMap = new TreeMap<Character,Integer>(new ValueComparator(hashMap));
for (Character key : string.toCharArray())
{
Integer value = hashMap.get(key);
if (value == null)
hashMap.put(key,1);
else
hashMap.put(key,value+1);
}
treeMap.putAll(hashMap);
for (Character key : treeMap.keySet())
{
Integer value = hashMap.get(key);
for (Integer i=0; i<value; i++)
System.out.print(key);
}
}
private class ValueComparator implements Comparator<Character>
{
Map<Character,Integer> base;
public ValueComparator(Map<Character,Integer> base)
{
this.base = base;
}
public int compare(Character a,Character b)
{
if (base.get(a) >= base.get(b))
return -1;
else
return +1;
}
}