Skip to content

Commit 838b398

Browse files
committed
feat: solve No.1704
1 parent 0629ee0 commit 838b398

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# 1704. Determine if String Halves Are Alike
2+
3+
- Difficulty: Easy.
4+
- Related Topics: String, Counting.
5+
- Similar Questions: .
6+
7+
## Problem
8+
9+
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half.
10+
11+
Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters.
12+
13+
Return `true`** if **`a`** and **`b`** are **alike****. Otherwise, return `false`.
14+
15+
 
16+
Example 1:
17+
18+
```
19+
Input: s = "book"
20+
Output: true
21+
Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
22+
```
23+
24+
Example 2:
25+
26+
```
27+
Input: s = "textbook"
28+
Output: false
29+
Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.
30+
Notice that the vowel o is counted twice.
31+
```
32+
33+
 
34+
**Constraints:**
35+
36+
37+
38+
- `2 <= s.length <= 1000`
39+
40+
- `s.length` is even.
41+
42+
- `s` consists of **uppercase and lowercase** letters.
43+
44+
45+
46+
## Solution
47+
48+
```javascript
49+
/**
50+
* @param {string} s
51+
* @return {boolean}
52+
*/
53+
var halvesAreAlike = function(s) {
54+
var map = {
55+
a: true,
56+
e: true,
57+
i: true,
58+
o: true,
59+
u: true,
60+
A: true,
61+
E: true,
62+
I: true,
63+
O: true,
64+
U: true,
65+
};
66+
var half = s.length / 2;
67+
var count = 0;
68+
for (var i = 0; i < half; i++) {
69+
if (map[s[i]]) count++;
70+
if (map[s[i + half]]) count--;
71+
}
72+
return count === 0;
73+
};
74+
```
75+
76+
**Explain:**
77+
78+
nope.
79+
80+
**Complexity:**
81+
82+
* Time complexity : O(n).
83+
* Space complexity : O(1).

0 commit comments

Comments
 (0)