提问者:小点点

在字符串中查找单词重复,而无需在Java中使用Hashmap,HashSet等


我有下面的代码,它可以在没有HashMap,HashSet等的字符串中找到重复项。但是我想要一个比这个更好的解决方案。请帮助我是Java编程新手。我相信Java足够强大,可以提供这一点。这并不是说我试图在Java集合中避免HashMap等。我只是想要一个更好的解决方案

public class practice {
    static void countWords(String st){
         //split text to array of words
         String[] words=st.split("\\s");
       //frequency array
         int[] fr=new int[words.length];
       //init frequency array
         for(int i=0;i<fr.length;i++)
           fr[i]=0;
         //count words frequency
         for(int i=0;i<words.length;i++){
           for(int j=0;j<words.length;j++){
             if(words[i].equals(words[j])) 
               {
                 fr[i]++;

                    }
                }
               }

         //clean duplicates
           for(int i=0;i<words.length;i++){
             for(int j=0;j<words.length;j++){
               if(words[i].equals(words[j])) 
               {
                 if(i!=j) words[i]="";

               }
         }
         }

    //show the output

    int total=0;
    System.out.println("Duplicate words:");
    for(int i=0;i<words.length;i++){

    if(words[i]!=""){


    System.out.println(words[i]+"="+fr[i]);

    total+=fr[i];

    }    
       }

    System.out.println("Total words counted: "+total);
     }


    public static void main(String[] args) {
        // TODO Auto-generated method stub
           countWords("apple banna apple fruit sam fruit apple hello hi hi hello hi");  
    }

}

共3个答案

匿名用户

尽管Hashmap和Hashset最适合这一要求。但如果你不想使用它,你也可以更有效地实现同样的目标:

    < li >将句子拆分成数组,然后使用Array.sort()按字母顺序(第一个字母)排序;。排序后,您可以遍历数组,并在线性时间内存储单词的重复计数。 < li >使用尝试数据结构。

匿名用户

您可以使用 Java8 流在单行代码中编写整个 countWords 方法(遵循内联注释):

static void countWords(String st){
  Map<String, Long> wordsAndCounts = 
     Arrays.stream(st.split("\\s")).    //Splt the string by space i.e., word
         collect(Collectors.groupingBy( //Apply groupby
         Function.identity(),          //Map each word
         Collectors.counting()         //Count how many words
     ));
    System.out.println(wordsAndCounts);
}

输出:

{banna=1, hi=3, apple=3, fruit=2, hello=2, sam=1}

匿名用户

public static void main(String[] args) {
        String s = "abcabcc abc abcdeffrgh";
        char[] ch = s.toCharArray();
        String temp = "";
        int j = 0;
        for (int i = 0; i < s.length(); i++) {
            int count = 0;
            char result = 0;
            for (j = 0; j < s.length(); j++) {
                if (ch[i] == ch[j]) {
                    result = ch[i];
                    count = count + 1;
                } else {
                    result = ch[i];
                }
            }
            if (!temp.contains(Character.toString(ch[i]))) {
                temp = temp + ch[i];
                System.out.println(result + "--count--" + count);
            }

        }
    }