簡體   English   中英

C#將字母轉換為數字以進行二進制搜索

[英]c# converting letters to numbers for binary search

學習搜索算法。 我對這個問題可能會導致什么感興趣,以及您對我的建議有何建議對此感興趣。 您知道任何快速方法,參考資料等嗎? 您可以添加的任何深度都很棒。

我對字母進行編碼以進行二進制搜索,它依賴於字符串,例如

(偽代碼)

        "indent = 0, A = 1, B = 2, C = 3, D = 4" 

因此字符串“ bab dab”將返回2120412。

然后將數字放入某種包含類似於以下算法的方法中:

(偽示例)

        int min = 0;
        int N =  total.Length;
        int max = N - 1;
        do
        {
            int mid = (min + max) / 2;
            if (searchKey > total[mid])
                min = mid + 1;
            else
                max = mid - 1;
            if (total[mid] == searchInp)
                return mid;

        } while (min <= max);
        return -1;

是的,您可以將char轉換為int ,這將為您提供字符的ASCII值 例如,A = 65,a = 97,等等。這是一個代碼示例來說明這一點(您可以對其進行調整以滿足自己的目的):

private static int[] StringToIntArray(string str)
    {
        List<int> ints = new List<int>();

        foreach (char chr in str)
        {
            // Technically you don't have to be explicit about the cast but I include it here for clarity
            int chrAsInt = (int)chr;

            // Do the following if you don't care about capital vs. lowercase
            // Otherwise, tweak the numbering system a little
            if (chrAsInt >= 97)
            {
                ints.Add(chrAsInt - 96);
            }
            else
            {
                ints.Add(chrAsInt - 64);
            }
        }

        return ints.ToArray();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM