开发者

Finding chars in a string using Hash table

I decided to solve the problem of finding given characters in a string. And I solved it in two ways:

The first(using hash-table to keep the values in ASCII for the chars we want to find):

static void Hash(string text, char[] charsToFind)
{
    Dictionary<int,char> chars = new Dictionary<int,char>();
    foreach (var letter in charsToFind)
    {
        chars[(int)letter] = letter;
    }

    foreach (var letter in text)
    {
        if (chars.ContainsKey((int)letter))
        {
            if (letter == chars[(int)letter])
            {
                Console.WriteLine("Element found at: {0}, value: {1}", (int)letter, letter);
            }
        }
    }
}

And the second way (th开发者_StackOverflowe naive):

static void Naive(string text, char[] charsToFind)
{
    foreach (var letter in text)
    {
        foreach (var character in charsToFind)
        {
            if ((int)letter == (int)character)
            {
                Console.WriteLine("Element found at: {0}, value: {1}", (int)letter, letter);
            }
        }
    }
}

And everything works fine! The question I'd like to ask is which one is the better and if there are even better solutions to this problem?

Thanks in advance!


Using LINQ:

string input = "abc";
char[] charsToFind = new[] { 'a', '1', 'b' };
IEnumerable<int> ids = charsToFind.Select(ch => input.IndexOf(ch)); // { 0, -1, 1 }

With Hashset<T> which is generic hash table:

HashSet<char> set = new HashSet<char>(input.ToCharArray());
...


The first one is a better approach, but the second one will probably be faster for a small number of characters.

Some comments on the first one. In the first one, using a dictionary involves cost of calculating the hash and performing a lookup. If you knew the chars were ASCII, you could use an array to speed up the lookup.

Rather than doing a 'ContainsKey' you could do a 'TryGetValue' to only lookup once.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜