gpt4 book ai didi

java - 有字符串 "naveen",希望输出为 "eennav"

转载 作者:行者123 更新时间:2023-12-02 09:51:07 25 4
gpt4 key购买 nike

我在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);
}
}

关于java - 有字符串 "naveen",希望输出为 "eennav",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56319266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com