在字符串中查找单词duplicate,而不使用Java中的Hashmap,HashSet等

时间:2017-04-29 07:25:44

标签: java string hashmap duplicates

我有以下代码,它在没有HashMap,HashSet等的字符串中找到重复项,但我想要一个比这个更好的解决方案。 请帮助我是Java编程的新手。我相信Java足够强大 P.S-不是我想在Java Collections中避免使用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 个答案:

答案 0 :(得分:2)

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

  1. 将句子拆分为数组,然后使用Array.sort();按字母顺序(第一个字母)对其进行排序。 排序后,您可以遍历数组并以线性时间存储重复的单词计数。
  2. 使用tries数据结构。

答案 1 :(得分:0)

您可以使用Java8 streams在单行代码中编写整个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}

答案 2 :(得分:0)

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

        }
    }
相关问题