【发布时间】:2017-09-27 07:49:35
【问题描述】:
我有下面的代码,它确实在没有 HashMap、HashSet 等的字符串中找到重复项,但我想要一个比这个更好的解决方案。 请帮助我是Java编程的新手。我相信 Java 足够强大,可以做到这一点 P.S-这并不是说我试图在 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");
}
}
【问题讨论】:
标签: java string hashmap duplicates