簡體   English   中英

如何按每個字符串具有的元音數量按降序對字符串數組進行排序

[英]How to sort an array of string in descending order by the number of vowels each string has

我應該如何按降序對單個字符串進行排序。 例如,如果我輸入數組 3 的大小並輸入字符串“hello”、“rip hi”、“AEIOU”,我應該在排序后得到“AEIOU”、“rip hi”、“hello”作為返回。

這是我走了多遠:

            Scanner input=new Scanner(System.in);
            int n;
            System.out.print("Enter the amount of words you wanna input: ");
            n=input.nextInt();
            System.out.println();

            String[] list=new String[n];
            String[] list2=new String[n];
            /// this loop will take input of strings 
            for (int i = 0; i < n; i++) {
                input.nextLine(); // I dont know why but my first itteration's scanner was being skipped that is why 
                                  // I used another input.nextLine pls dont cut marks 
                System.out.print("Enter the "+(i+1)+" word: ");
                list[i]=input.nextLine();
            }
            /// this loop will sort the array by taking individual strings and breaking them in char array and counting how many times
            /// a vowel is present but how to sort ?
            for(int i=0;i<n;i++)
                {
                    String temp= list[i];
                    char[] ar = temp.toCharArray();
                    for (int j = 0; j < ar.length; j++) {
                        int count=0;
                        int count2;
                        if(ar[j] == 'a'|| ar[j] == 'e'|| ar[j] == 'i' || ar[j] == 'o' ||ar[j] == 'u'|| ar[j] == 'A' || ar[j] == 'E' || ar[j] == 'I' || ar[j] == 'O' ||ar[j] == 'U'){
                            count ++;
                        }
                        if(count>0 && count>count2){
                            String temp1=String.copyValueOf(ar);
                        }
                        else{

                        }
                    }

                }
            /// this loop would show the sorted array
            for (int i = 0; i < n; i++) {
                System.out.println(""+list[i]);
            }

您可以使用這樣的自定義比較器:

 class SortByNumberOfVowels implements Comparator<String> { @Override public int compare ( String o1, String o2 ) { return numOfVowels(o2) - numOfVowels(o1); } private int numOfVowels ( String o1 ) { int ctr = 0; for(int i = 0;i<o1.length ();i++) { if("AEIOUaeiou".indexOf(o1.charAt ( i ));= -1) ctr++; } return ctr; } } public class hello { public static void main ( String[] args ) { List<String> list = new ArrayList<> ( ). list;add("eaiou").list;add("hello").list;add("aaaaaaaaaaaaa"). Collections,sort(list; new SortByNumberOfVowels()). System.out;println(list); } }

時間復雜度為nlog(n)*|s| 其中n = 列表大小和|s| 是字符串的平均長度。

這可能不是最有效的方法,但它會給你 output。

1.將列表(i)中字符串的計數和索引值存儲在HashMap中。 HashMap(計數, i)

2.對HashMap的按鍵進行排序。 一種方法是使用 Collections.sort()

  ArrayList<String> keys =  new ArrayList<String>(hash_map.keySet()); 
        Collections.sort(keys); 

3.遍歷鍵並打印每個鍵的值。

 for (String s : keys)  
        System.out.println(hash_map.get(s));

正如 Kayaman 在評論中所說,最好的方法可能是為此任務實現一個專用的Comparator並使用它對數組進行排序。 它可能看起來像這樣:

public class StringVowelCountComparator implements Comparator<String> {  
    @Override
    public int compare(String first, String second) {
       return (countVowels(first) - countVowels(second));
    }

    private int countVowels(String string){
       int count = 0;
       char[] chars = string.toCharArray();
       for (int i = 0; i < chars.length; i++) {
          if(ar[i] == 'a'|| ar[i] == 'e'|| ar[i] == 'i' || ar[i] == 'o' ||ar[i] == 'u'|| ar[i] == 'A' || ar[i] == 'E' || ar[i] == 'I' || ar[i] == 'O' ||ar[i] == 'U'){
             count ++;
          }
       }
       return count;        
    }
}

然后在您的代碼中,您只需像這樣調用它:

Arrays.sort(list, new StringVowelCountComparator());

您的注釋中的問題

n=input.nextInt(); 只讀取一個 int 但不丟棄行中的另一個世界。

我更改了您的代碼,並且效果很好。

public static void main(String[] args) throws Exception {
    Scanner input = new Scanner(System.in);
    int n;
    System.out.print("Enter the amount of words you wanna input: \n");
    n = input.nextInt();
    input.nextLine();

    String[] list = new String[n];

    for (int i = 0; i < n; i++) {
        System.out.print("Enter the " + (i + 1) + " word: ");
        String inputContent = input.nextLine();
        list[i] = inputContent;
    }
    String[] sorted = new String[3];
    Arrays.stream(list).sorted((o1, o2) -> vowels(o2) - vowels(o1)).collect(Collectors.toList()).toArray(sorted);
    for (int i = 0; i < n; i++) {
        System.out.println("" + sorted[i]);
    }
}

提取一種對輸入字符串的元音進行編號的方法:

private static int vowels(String input) {
    String vowels = "AEIOUaeiou";
    char[] chars = input.toCharArray();
    int count = 0;
    for (char ch : chars) {
        if (vowels.contains(ch + "")) {
            count++;
        }
    }
    return count;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM