Wednesday, February 17, 2021

Leetcode Everyday: 1684. Count the Number of Consistent Strings. Easy

public class Solution {
     public int CountConsistentStrings(string allowed, string[] words) =>
         words.Count(word => !word.Any(wc => allowed.IndexOf(wc) == -1));
}
Solution 2, faster and still readable:
public class Solution {
    public int CountConsistentStrings(string allowed, string[] words) {
        int count = 0;
        foreach (string word in  words) {     
            foreach (char c in word) {          
              if (allowed.IndexOf(c) == -1) {
                 goto nextWord;
              }
            }
            ++count;
        nextWord:;
        }
        return count;
    }
}
Solution 2b, goto-less:
public class Solution {
    public int CountConsistentStrings(string allowed, string[] words) {
        int count = words.Length;
        foreach (string word in  words) {     
            foreach (char c in word) {          
              if (allowed.IndexOf(c) == -1) {
                 --count;
                  break;
              }
            }
        }
        return count;
    }
}
Solution 3, goto when used judiciously makes for a faster code. This is the fastest C# code on leetcode. Optimized other's code by converting boolean+break combo to a goto:
public class Solution {
    public int CountConsistentStrings(string allowed, string[] words) {
        bool[] valid = new bool[26];

        foreach (char c in allowed) valid[c - 'a'] = true;

        int count = 0;
        foreach (var word in words) {
            foreach (char c in word) if (!valid[c - 'a']) goto nextWord;
            
            ++count;            
        nextWord:;
        }
        
        return count;
    }
}
Solution 4, almost same as above, fastet code too. Just reversed the logic, something is valid until it is not. So the count starts with words.Length. made it goto-less
public class Solution {
    public int CountConsistentStrings(string allowed, string[] words) {
        bool[] valid = new bool[26];

        foreach (char c in allowed) valid[c - 'a'] = true;

        int count = words.Length;
        foreach (var word in words) {
            foreach (char c in word) {
                if (!valid[c - 'a']) {
                    --count;
                    break;
                }
            }
        }
        
        return count;
    }
}
Source: https://leetcode.com/problems/count-the-number-of-consistent-strings/

No comments:

Post a Comment