public static int countVowels(String[] ar1){ // this method counts
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)){
a++;
}
}
}
return a;
}
}
7 Réponses :
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;
}
EDITalright now i fixed the error and edited the variablenames to make a bit more sense. although this is O(n*m) i believe (where n is the ammount of strings and m is the ammount of char the longest string has) (not so good complexity) it gets the job done ar1 in this case is your input of strings, ar2 are just the vowels that exist.so you go through every string in ar1 and set "vowelPerWord" to 0, go through every single char in every string and check if it is a vowel increase the vowelPerWord by 1. at the end, after you went through every char of that string you check if there were 3 or more vowels, if so increase the totalWordsWithThreeVowels, which at the end is returned.
Veuillez expliquer ce que fait cette méthode et peut-être aussi clarifier pourquoi vous avez 3 boucles for et ce que font exactement a et b
Attendez, je corrige une erreur dans le code ci-dessus en ce moment
La boucle supplémentaire augmentera la complexité du code.
la troisième boucle (la plus interne) sera toujours O (6) donc nous pouvons théoriquement l'ignorer
Bien que la boucle la plus interne ne soit en effet que 6, s'il y a, disons, 1000 mots, la boucle la plus interne de 6 fait passer le nombre d'itérations de 1 000 000 à 6 000 000 .. Le problème avec la boucle imbriquée, aussi petite soit-elle, est que la complexité augmente de façon exponentielle. Il s'agit actuellement de la complexité O (6 * N ^ 2) , où N est la quantité de mots dans ar1 . PS: La voyelle-boucle de 6 n'est en effet pas vraiment le problème ici, c'est la boucle imbriquée de deux fois le ar1 .
ouais je sais, je viens de donner la solution la plus simple à coder, pas d'expressions rationnelles étranges, car la tâche ressemblait plus à une tâche de type débutant
@Alan Je suis d'accord. Bien que je résoudrais personnellement aussi cela avec un lambda et une regex Java 8, pour un débutant, il est préférable d'avoir une modification mineure du code qu'ils ont déjà afin qu'ils puissent en tirer des leçons. Je n'ai utilisé aucune expression régulière dans ma réponse.
Vous pouvez utiliser la correspondance régulière pour trouver si une chaîne contient un ensemble de caractères. Par exemple, si vous voulez savoir si une chaîne contient une des voyelles, vous pouvez utiliser:
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;
}
EDIT:
Donc, votre code ressemblerait à:
String str = "yydyrf";
boolean contains = str.toLowerCase().matches(".*[aeiou].*");
System.out.println(contains);
Bien que ce soit effectivement un moyen plus facile que la boucle et contient, cela ne répond pas à la question d'OP.
Ce dont vous avez besoin est une boucle et un décompte supplémentaires. Quelque chose comme ceci:
// 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;
}
Une autre solution avec la méthode replaceAll .
L'idée principale est de soustraire à word.length () la même longueur de mot sans voyelles. Et vérifiez la différence.
long count = Arrays.stream(words)
.filter(s -> s.toLowerCase().matches("(.*[aeyiuo].*){3,}"))
.count();
Ou vous pouvez utiliser matches () comme @pkgajulapalli l'a suggéré. Cela peut être assez concis avec l'API de flux:
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;
}
Actuellement, ne fonctionne pas avec les voyelles majuscules, utilisez s.toLowerCase () ou le groupe d'expression régulière [AaEeYyIiUuOo]
Oh et pour des raisons de performances, vous pouvez utiliser un Pattern prédéfini enregistré dans une variable statique ou quelque chose, puis utiliser pattern.matcher (s) .replaceAll ("") : )
Vous pouvez utiliser ceci:
public static int countVowels(String[] words) {
char[] chars = {'a', 'e', 'i', 'u', 'y', 'o'};
int wordsWith3Vowels = 0;
for (String word : words) {
int countedVowels = 0;
for (char s : chars) {
if (word.toLowerCase().indexOf(s) != -1) {
countedVowels++;
}
}
if (countedVowels >= 3) {
wordsWith3Vowels++;
}
}
return wordsWith3Vowels;
}
Qui utilise des char s au lieu de String s qui est un peu plus rapide
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;
}
Depuis java-8 , vous pouvez désormais utiliser Streams.
String[] values = {"AA","BC","CD","AE"};
boolean contains = Arrays.stream (values) .anyMatch ("s" :: equals) ;
Pour vérifier si un tableau de int , double ou long contient une valeur utilisez respectivement IntStream , DoubleStream ou LongStream .
Exemple int [] a = {1,2,3,4}; boolean contient = IntStream.of (a) .anyMatch (x -> x == 4);