首页 > 解决方案 > 有字符串 "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]);
            }

标签: javastring

解决方案


假设问题是要求我们取一个只包含小写字母的字符串,并按字母的频率(从高到低)和按字母顺序组织它们,我们可以按如下方式进行。该策略首先遍历输入字符串的字符并计算每个字符的出现次数。然后我们查看字母的计数并找到最大的。从最大到 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);
    }
}

推荐阅读