java - 有字符串 "naveen" ,希望输出为 "eennav"
问题描述
我在java“naveen”中有字符串,我想输出为“eennav”。请帮我解决这个问题。这个想法是字符将按频率顺序排列,并且在频率相同的情况下,按字母顺序排列。
谢谢
我试图在字符串中查找重复项,但无法获得所需的输出。
String str="naveen";
int count =0;
char[] charr=str.toCharArray();
for(int i=0;i<charr.length;i++) {
//System.out.println(s[i]);
for(int j=i+1;j<charr.length;j++) {
if(charr[i]==(charr[j])) {
System.out.println(charr[i]);
}
解决方案
假设问题是要求我们取一个只包含小写字母的字符串,并按字母的频率(从高到低)和按字母顺序组织它们,我们可以按如下方式进行。该策略首先遍历输入字符串的字符并计算每个字符的出现次数。然后我们查看字母的计数并找到最大的。从最大到 1,我们遍历出现多次的字符的字母表,并将其中许多字符附加到结果字符串中。这里涉及到从 'a' 到 0 和 0 到 'a' 等来回转换到 25 和 'z' 的一些工作。这种方法可以扩展,但由于问题没有具体说明,我选择进行简化假设。我也没有进行优化,
public class MyClass {
public static void main(String args[]) {
String str = "naveen"; //this string may change, but it is assumed to be all lower case letters by this implementation
int[] counts = new int[26]; //frequency count of letters a to z
for (int i = 0; i < 26; i++) {
counts[i] = 0; // intially 0 of any letter
}
char[] charr = str.toCharArray();
for (int i = 0; i < charr.length; i++) {
counts[(int)(charr[i]) - (int)('a')]++; // increment corresponding spot in counts array, spot 0 for 'a' through 25 for 'z'
}
int maxCount = counts[0]; // now find the most occurrences of any letter
for (int i = 1; i < counts.length; i++) {
if (counts[i] > maxCount) {
maxCount = counts[i];
}
}
String result = ""; // string to return
for (int j = maxCount; j > 0; j--) { // work down from most frequently occuring, within that alphabetically
for (int i = 0; i < 26; i++) {
if (counts[i] == j) {
//System.out.println("there are "+j+" of the letter "+(char)((int)('a'+i)));
for (int k = 0; k < j; k++) {
result = result + (char)((int)('a' + i));
}
};
}
}
System.out.println(result);
}
}
推荐阅读
- node.js - while循环api调用并将响应存储在nodejs中的数组中
- angular - 如何在嵌套 *ngFor 中使用单个 FormArray?
- pytorch - 为什么 Pytorch Transformer 模块中 MultiheadAttention 的输入大小是 1536?
- javascript - 以 CSV 格式加载 D3.JS 树图
- c++ - C++ 分段错误访问双向链表中的“prev”指针
- android - 通过 findById 访问活动布局中的硬编码片段
- sql - 如何匹配 2 列中的员工 ID 并将它们分组到一个数组中?
- php - 如何将 SQL 结果的 while 循环定义为循环?
- c++ - 在 C++ 中构造复合 Protobuf 消息
- java - 从名字,姓氏到姓氏,名字打印名字和姓氏