-
Notifications
You must be signed in to change notification settings - Fork 0
/
[26-w6-d1]vowels.js
67 lines (61 loc) · 1.23 KB
/
[26-w6-d1]vowels.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//Problem: write a function that returns the count of vowels in a string.
//Vowels are the letters a, e, i, o, u.
//Examples:
//vowels('Hello'); //2
//vowels('cOderbytE'); //3
//Solutions:
//#1
// O(n^2)
function vowels(str) {
let counter = 0;
let vowelsChecker = 'aeiou';
let lowercase = str.toLowerCase();
for (let i = 0; i < lowercase.length; i++) {
if (vowelsChecker.includes(lowercase[i])) {
counter++;
}
}
return counter;
}
//#2
// O(n) linear time complexity
function vowels(str) {
let counter = 0;
const obj = {
a: true,
e: true,
i: true,
o: true,
u: true,
};
let lowercase = str.toLowerCase();
for (let i = 0; i < lowercase.length; i++) {
if (lowercase[i] in obj) {
counter++;
}
}
return counter;
}
//#3
function vowels(str) {
let count = 0;
let regex = new RegExp('[aAeEIioOuU]');
for (let i = 0; i < str.length; i++) {
if (regex.test(str[i])) {
count += 1;
}
}
return count;
}
//#4
const checkVowel = (char) => {
return (
char == "a" || char == "e" || char == "i" || char == "o" || char == "u"
);
};
const vowels = (str) => {
let count = 0;
let lowercase = str.toLowerCase()
for (let i = 0; i < lowercase.length; i++) if (checkVowel(lowercase[i])) ++count;
return count;
};