Swift Leetcode Series: Determining if two String halves are alive

April Leetcoding Challenge 2021: Day 7

Problem Description

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.

Example 1:

Input: s = "book"
Output: true
Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.

Example 2:

Input: s = "textbook"
Output: false
Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.

Example 3:

Input: s = "MerryChristmas"
Output: false

Example 4:

Input: s = "AbCdEfGh"
Output: true

Constraints

  • 2 <= s.length <= 1000
  • s.length is even.
  • s consists of uppercase and lowercase letters.

Solution

One thing that comes into find is that we would be checking the counts of the vowels. We can use any collection like an array or dictionary to check since vowels are limited are not much so it is constant time. Also, we should either add both lowercase and uppercase vowels or we can add only the lowercase and while comparing we check the lowercased() character in the collection.

Algodaily.com

Code

Complexity Analysis

Time = O(N) (Every element is visited once for comparison)

Senior iOS Engineer. Writer at https://theswiftnerd.com