lundi 1 septembre 2025

public static string FactorizeExtremities(string str1, string str2)

 Chercher la plus longue sous-chaîne qui est à la fin de str1 et au début de str2.

Faire de même pour str2 à la fin et str1 au début.

Choisir l’ordre qui factorise le plus de caractères.

Si les deux factorisations sont égales, privilégier str1 + str2.

Retourner la concaténation avec factorisation.



=======================

public static string FactorizeExtremities(string str1, string str2)

{

    // Fonction interne pour calculer le maximum de recouvrement suffixe/prefixe

    int MaxOverlap(ReadOnlySpan<char> a, ReadOnlySpan<char> b)

    {

        int max = 0;

        int minLen = Math.Min(a.Length, b.Length);

        for (int len = 1; len <= minLen; len++)

        {

            if (a.Slice(a.Length - len, len).SequenceEqual(b.Slice(0, len)))

                max = len;

        }

        return max;

    }


    ReadOnlySpan<char> span1 = str1.AsSpan();

    ReadOnlySpan<char> span2 = str2.AsSpan();


    int overlap1 = MaxOverlap(span1, span2); // str1 + str2

    int overlap2 = MaxOverlap(span2, span1); // str2 + str1


    if (overlap1 > overlap2 || overlap1 == overlap2)

    {

        // str1 + str2

        return str1 + str2.Substring(overlap1);

    }

    else

    {

        // str2 + str1

        return str2 + str1.Substring(overlap2);

    }

}


============================
public static string FactorizeExtremities(string str1, string str2)
{
    int maxOverlap(string a, string b)
    {
        int max = 0;
        int minLen = Math.Min(a.Length, b.Length);
        for (int len = 1; len <= minLen; len++)
        {
            if (a.Substring(a.Length - len) == b.Substring(0, len))
                max = len;
        }
        return max;
    }

    int overlap1 = maxOverlap(str1, str2); // str1 + str2
    int overlap2 = maxOverlap(str2, str1); // str2 + str1

    if (overlap1 > overlap2 || overlap1 == overlap2)
    {
        return str1 + str2.Substring(overlap1);
    }
    else
    {
        return str2 + str1.Substring(overlap2);
    }
}


Aucun commentaire:

Enregistrer un commentaire