C# using HashSet

  • 0

    Just learned that "substring" problems should use HashSet due to its O(1) search feature (e.g. "rolling hash" is used to to search text in a long document).

    This is simply a "brute force" solution utilizing the C# internal hash(str) function (or something like that). Looks like this code is very fast as the submission shows a ~94% beat rate:

        public int StrStr(string haystack, string needle) {
            HashSet<string> hash = new HashSet<string>();
            if (hash.Contains(haystack))
                return 0;
            int len = needle.Length;
            for (int i=0; i<haystack.Length && haystack.Length-i>=len;i++)
                if (hash.Contains(haystack.Substring(i, len)))
                    return i;
            return -1;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.