Monday, March 8, 2021

Leetcode Everyday: 1704. Determine if String Halves Are Alike. Easy

public class Solution {
    public bool HalvesAreAlike(string s) {
        var half = s.Length / 2;
        var a = s.Substring(0, half);
        var b = s.Substring(s.Length - half, half);
        
        var vowels = new HashSet<char>() {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
        
        return a.Count(c => vowels.Any(v => char.ToUpper(c) == v))
            == b.Count(c => vowels.Any(v => char.ToUpper(c) == v));
    }
}
Optimized:
public class Solution {
    public bool HalvesAreAlike(string s) {
        var half = s.Length / 2;        
        var vowels = new HashSet<char>() {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
                
        var count = 0;        
        for (var i = 0; i < half; ++i) {
            if (vowels.Contains(s[i]))
                ++count;
            
            if (vowels.Contains(s[^(i + 1)])) 
                --count;
        }        
        return count == 0;
    }
}
public class Solution {
    public bool HalvesAreAlike(string s) {
        var half = s.Length / 2;        
                
        var count = 0;        
        for (var i = 0; i < half; ++i) {
            if (s[i] switch {
                'A' => true,
                'a' => true,
                'E' => true,
                'e' => true,
                'I' => true,
                'i' => true,
                'O' => true,
                'o' => true,
                'U' => true,
                'u' => true,
                _ => false                    
            }) {
                ++count;
            }
            
            if (s[(^(i + 1))] switch {
                'A' => true,
                'a' => true,
                'E' => true,
                'e' => true,
                'I' => true,
                'i' => true,
                'O' => true,
                'o' => true,
                'U' => true,
                'u' => true,
                _ => false                    
            }) {
                --count; 
            }
        }        
        return count == 0;
    }
}
Source: https://leetcode.com/problems/determine-if-string-halves-are-alike/

No comments:

Post a Comment