本文介绍了字符串按降序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人知道如何将afacfa转换为aaaffc吗? (频率降序) 我对编程非常陌生,只能提出建议.
Does anyone know how to sort a string eg: afacfa into aaaffc? (descending order of frequency) I am very new to programming and have only been able to come up with.
String word = (String)jTextField1.getText(); String indexes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; int[] count = new int[indexes.length()]; for (int i = 0; i < word.length(); i++) { int index = indexes.indexOf(word.charAt(i)); System.out.println( "" + i + count[2] ) ; if (index < 0) continue; count[index]++; } for (int i = 0; i < count.length; i++) { if (count[i] < 1) continue; jTextArea1.append(String.format("%s (%d) %s",indexes.charAt(i),count[i], new String(new char[count[i]]).replace('\0', '*')));推荐答案
如果您熟悉哈希映射,则此代码将轻松完成您想要的操作. 哈希表的值是频率计数器,它通过在哈希表内找到最大值来打印输出.
If you are familiar with hash maps, this code will easily do what you want. The hashmap value is the frequency counter and it prints the output by finding the max value inside the hashmap.
import java.util.Arrays; import java.util.HashMap; public class FrequencyPrint { public static void main(String[] args) { String s = "ccrrcdcffcghijk"; HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>(); for (int i = 0; i < s.length(); i++) { if (hashMap.containsKey(s.charAt(i))) { int value = hashMap.get(s.charAt(i)); hashMap.put(s.charAt(i), ++value); } else { hashMap.put(s.charAt(i), 1); } } Character keys[] = Arrays.copyOf(hashMap.keySet().toArray(), hashMap .keySet().toArray().length, Character[].class); Integer values[] = Arrays.copyOf(hashMap.values().toArray(), hashMap .values().toArray().length, Integer[].class); for (int i = 0; i < keys.length; i++) { int x = FrequencyPrint.findmax(values); for (int j = 0; j < values[x]; j++) { System.out.print(keys[x]); } values[x] = 0; } } public static int findmax(Integer values[]) { int max = 0; for (int i = 0; i < values.length; i++) { if (values[i] > values[max]) { max = i; } } return max; } }更多推荐
字符串按降序排列
发布评论