5 回答

TA贡献1804条经验 获得超3个赞
另一种解决replaceAll方法。主要思想是从word.length()没有元音的相同词长中减去。并检查差异。
public static int countVowels(String[] ar1){
int a = 0;
for (String word : ar1) {
int i = word.length() - word.toLowerCase().replaceAll("[aeyiuo]", "").length();
if (i >= 3) {
a++;
}
}
return a;
}
或者您可以matches()按照@pkgajulapalli 的建议使用。使用流 api 可以非常简洁:
long count = Arrays.stream(words)
.filter(s -> s.toLowerCase().matches("(.*[aeyiuo].*){3,}"))
.count();

TA贡献1900条经验 获得超5个赞
public static int countVowels(String[] ar1) { // this method counts
int vowelPerWord = 0;
int totalWordsWithThreeVowels = 0;
char[] ar2 = new char[] { 'a', 'e', 'i', 'u', 'y', 'o' };
for (int i = 0; i < ar1.length; i++) {
vowelPerWord = 0;
for (int j = 0; j < ar1[i].length(); j++) {
for (int k = 0; k < ar2.length; k++) {
if (ar2[k] == (ar1[i].charAt(j))) {
vowelPerWord++;
}
}
}
if (vowelPerWord >= 3) {
totalWordsWithThreeVowels++;
}
}
return totalWordsWithThreeVowels;
}
编辑
好吧,现在我修复了错误并编辑了变量名以使其更有意义。虽然这是 O(n*m) 我相信(其中 n 是字符串数,m 是最长字符串的字符数)(不太复杂)它可以完成工作 ar1 在这种情况下是您的输入字符串,ar2 只是存在的元音。
因此,您遍历 ar1 中的每个字符串并将“vowelPerWord”设置为 0,遍历每个字符串中的每个字符并检查它是否是元音,将 vowelPerWord 增加 1。最后,在您遍历该字符串的每个字符之后您检查是否有 3 个或更多元音,如果有,则增加 totalWordsWithThreeVowels,最后返回。

TA贡献1829条经验 获得超6个赞
你需要的是一个额外的循环和计数。像这样的东西:
// This method counts how many words have at least 3 vowels
public static int countVowels(String[] wordsArray){
int atLeastThreeVowelsCount = 0;
for(String word : wordsArray){
int vowelCount = 0;
for(String vowel : new String[]{ "a", "e", "i", "u", "y", "o" }){
if(word.toLowerCase().contains(vowel)){
vowelCount++;
}
}
if(vowelCount >= 3){
atLeastThreeVowelsCount++;
}
}
return atLeastThreeVowelsCount;
}
请注意,我还为变量提供了一些更有用的名称,而不是ar1,s等,因此更容易阅读正在发生的事情。

TA贡献1966条经验 获得超4个赞
您可以使用正则表达式匹配来查找字符串是否包含任何字符集。例如,如果要查找字符串是否包含任何元音,可以使用:
String str = "yydyrf";
boolean contains = str.toLowerCase().matches(".*[aeiou].*");
System.out.println(contains);
编辑:
所以你的代码看起来像:
public static int countVowels(String[] ar1) {
int a = 0;
String[] ar2 = new String[] { "a", "e", "i", "u", "y", "o" };
String pattern = ".*[" + String.join("", ar2) + "].*";
for (int i = 0; i < ar1.length; i++) {
if (ar1[i].matches(pattern)) {
a++;
}
}
return a;
}

TA贡献1911条经验 获得超7个赞
public static int countVowels(String[] ar1){ // this method counts
//Create hash map key = array string && value = vowels count
Map<String,Integer> mapVowels=new HashMap<String,Integer>();
int a = 0;
String[] ar2 = new String[]{"a", "e", "i", "u", "y", "o"};
for(int i = 0; i < ar1.length; i++){
for(String s : ar2){
if(ar1[i].toLowerCase().contains(s)){
//Check map string already has vowel count then increase by one
if(mapVowels.get(s)!=null) {
mapVowels.put(s,mapVowels.get(s)+1);
//After add the vowels count get actual count and check is it more than 3
if(mapVowels.get(s)>3)
a++;
}
else {
//If the vowels string new for map then add vowel count as 1 for first time
mapVowels.put(s,1);
}
}
}
}
return a;
}
添加回答
举报