一道简单的算法题

/// <summary>
/// 字符串str1与str2,若str1中的各个字符经过重排后能形成str2,则返回true。
/// str1 = "sawsdfdfalsraodf";
/// str2 = "world";
/// rearrange(str1,str2) -> true;
/// 
/// 提示:检查str1中的各个字符的字符数是否大于str2各个字符的字符数即可
/// </summary>
private static bool rearrange(string str1, string str2)
{
    if (str1 == null || str2 == null || str1.Length < str2.Length) return false;

    char[] chars = str1.ToCharArray();
    char[] chars2 = str2.ToCharArray();

    Dictionary<char, int> dic = new Dictionary<char, int>();
    foreach (var c in chars)
    {
        if (dic.ContainsKey(c))
        {
            dic[c] = dic[c] + 1;
        }
        else
        {
            dic[c] = 1;
        }
    }
    Dictionary<char, int> dic2 = new Dictionary<char, int>();
    foreach (var c in chars2)
    {
        if (dic2.ContainsKey(c))
        {
            dic2[c] = dic2[c] + 1;
        }
        else
        {
            dic2[c] = 1;
        }
    }

    foreach (var c in dic2.Keys)
    {
        if (!dic.ContainsKey(c)) return false;

        if (dic[c] < dic2[c]) return false;
    }
    return true;
}
posted @ 2023-07-26 11:25  xuxuzhaozhao  阅读(10)  评论(0编辑  收藏  举报