字符串按降序排列

编程入门 行业动态 更新时间:2024-10-26 21:34:07
本文介绍了字符串按降序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有人知道如何将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; } }

更多推荐

字符串按降序排列

本文发布于:2023-10-22 08:41:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1517011.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   排列   降序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!