[力扣] 算法 14 (C#)

14. 最长公共前缀

public class Solution {
    public string LongestCommonPrefix(string[] strs)
    {
        if (strs.Length == 0) return string.Empty;
        var ret = strs[0].AsSpan();
        foreach(var str in strs.AsSpan(1))
        {
            ret = LCP(ret, str);
            if (ret.Length == 0) break;
        }
        return ret.ToString();
    }
    
    static ReadOnlySpan<char> LCP(ReadOnlySpan<char> left, ReadOnlySpan<char> right)
    {
        if (left.Length > right.Length) return LCP(right, left);
        var to = 0;
        while(to < left.Length)
        {
            if (left[to] != right[to]) break;
            to++;
        }
        return left.Slice(0,to);
    }
}

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注