5 回答

TA貢獻1804條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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;
}
編輯
好吧,現(xiàn)在我修復了錯誤并編輯了變量名以使其更有意義。雖然這是 O(n*m) 我相信(其中 n 是字符串數(shù),m 是最長字符串的字符數(shù))(不太復雜)它可以完成工作 ar1 在這種情況下是您的輸入字符串,ar2 只是存在的元音。
因此,您遍歷 ar1 中的每個字符串并將“vowelPerWord”設置為 0,遍歷每個字符串中的每個字符并檢查它是否是元音,將 vowelPerWord 增加 1。最后,在您遍歷該字符串的每個字符之后您檢查是否有 3 個或更多元音,如果有,則增加 totalWordsWithThreeVowels,最后返回。

TA貢獻1829條經(jīng)驗 獲得超6個贊
你需要的是一個額外的循環(huán)和計數(shù)。像這樣的東西:
// 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等,因此更容易閱讀正在發(fā)生的事情。

TA貢獻1966條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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;
}
添加回答
舉報