-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexes_and_ohs.js
More file actions
53 lines (39 loc) · 1.06 KB
/
Copy pathexes_and_ohs.js
File metadata and controls
53 lines (39 loc) · 1.06 KB
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
// Exes and Ohs
// Solution 1
function XO(str) {
return str.toLowerCase().charAt('x').length === str.toLowerCase().charAt('o').length;
}
// Or...
function XO(str) {
// Initialize storage arrays (This works, but uses O(N) extra memory)
let x = [];
let o = [];
// Iterate over every character in the string
for (let i = 0; i < str.length; i++) {
// Check for 'x', case-insensitive
if (str[i].toLowerCase() === "x") {
x.push(str[i]); // Store the character
}
// Check for 'o', case-insensitive
else if (str[i].toLowerCase() === "o") {
o.push(str[i]); // Store the character
}
}
// Compare the number of items collected in each array
if (x.length === o.length) {
return true;
} else {
return false;
}
}
// Or...
function XO(str) {
// Single variable to track the "balance" between Xs and Os
let balance = 0;
for (let char of str.toLowerCase()) {
if (char === 'x') balance++;
if (char === 'o') balance--;
}
// If balance returns to 0, amounts were equal.
return balance === 0;
}