refactor: CheckVowels (#5393)

This commit is contained in:
Alex Klymenko 2024-08-25 22:14:33 +02:00 committed by GitHub
parent a5f57fbfde
commit 580aa0c9c5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 17 additions and 21 deletions

View File

@ -1,7 +1,5 @@
package com.thealgorithms.strings; package com.thealgorithms.strings;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set; import java.util.Set;
/** /**
@ -10,24 +8,24 @@ import java.util.Set;
* alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order * alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order
*/ */
public final class CheckVowels { public final class CheckVowels {
private static final Set<Character> VOWELS = Set.of('a', 'e', 'i', 'o', 'u');
private CheckVowels() { private CheckVowels() {
} }
private static final Set<Character> VOWELS = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
/** /**
* Check if a string is has vowels or not * Checks if a string contains any vowels.
* *
* @param input a string * @param input a string to check
* @return {@code true} if given string has vowels, otherwise {@code false} * @return {@code true} if the given string contains at least one vowel, otherwise {@code false}
*/ */
public static boolean hasVowels(String input) { public static boolean hasVowels(String input) {
if (input == null) { if (input == null || input.isEmpty()) {
return false; return false;
} }
input = input.toLowerCase();
for (int i = 0; i < input.length(); i++) { for (char c : input.toLowerCase().toCharArray()) {
if (VOWELS.contains(input.charAt(i))) { if (VOWELS.contains(c)) {
return true; return true;
} }
} }

View File

@ -1,17 +1,15 @@
package com.thealgorithms.strings; package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class CheckVowelsTest { class CheckVowelsTest {
@Test @ParameterizedTest
public void isVowel() { @CsvSource({"'foo', true", "'bar', true", "'why', false", "'myths', false", "'', false", "'AEIOU', true", "'bcdfghjklmnpqrstvwxyz', false", "'AeIoU', true"})
assertTrue(CheckVowels.hasVowels("foo")); void testHasVowels(String input, boolean expected) {
assertTrue(CheckVowels.hasVowels("bar")); assertEquals(CheckVowels.hasVowels(input), expected);
assertFalse(CheckVowels.hasVowels("why"));
assertFalse(CheckVowels.hasVowels("myths"));
} }
} }