基本上,我正准备接受采访,并且遵循一种政策,这种政权给我带来了很多挑战,这些挑战经常被采访。
这个特殊挑战的目标是计算在句子中出现不止一次的单词数量,不包括标点符号。我做到了,但我花了至少5分钟才拿出来并编码。
我不确定在java采访中编写类似这样的代码是否可以接受5分钟,所以我希望看到更简单的代码可能更少。以下是我解决它的方法。
System.out.println("Part 6 challenge-------------------------------------------------------------------------");
String sentence3 = "She's the queen and likes, apples APPLES, bananas BANANAS Bananas, and oranges ORANGE."; //original string
StringBuilder sb3 = new StringBuilder(); //declared string builder to build new string without punctuations
char [] punctuations = {'.',',',':','?','!',';'};//Char array containing punctuations to lookout for
for (int i=0; i<sentence3.length(); i++){
boolean p = false; //declared boolean within loop to turn on if punctuation was found in the original string
for (Character c: punctuations){
if (sentence3.charAt(i) == c){
p = true;// turn on
}
} if(!p){
sb3.append(sentence3.charAt(i));//if no punctuations found, add it to the string builder to build new string
}
}
String word[] = sb3.toString().split(" ");
Set<String> uniqueWords = new HashSet<>();
int count = 0;
for (String s: word) {
uniqueWords.add(s.toLowerCase());
}
for (String s: uniqueWords){
for (String w: word){
if (s.equals(w.toLowerCase())){
count++;
}
}
System.out.println(String.format("Found %s %d times", s, count));
count =0;
}
答案 0 :(得分:3)
更短的方式,概述:
Set<String>
替换为Map<String, Integer>
并按线性时间计算单词数量; 顺便说一句,如果您进入最小语句计数,则所有可以是一个流表达式。