任何框架的功能帮助找到多个字符串的最长的共同的出发子? [英] Any Framework functions helping to find the longest common starting substring of multiple strings?

查看:70
本文介绍了任何框架的功能帮助找到多个字符串的最长的共同的出发子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字符串(其代表路径和),其应该有一个共同的开头(根路径)的列表。我需要得到普遍开始。

I have a list of strings (which represent paths and) which should all have a common beginning (root path). I need to get that common beginning.

这只是几行扔在一起,但我有唠叨的感觉,这必须在今年抛出一百万次在一起,有可能是一个算法可用于这一点,但找不到东西的框架。结果
此外,我想这已经这么问过,但我想出了干。

That's just a couple of lines to throw together, but I have the nagging feeling that this must be thrown together a million times a year and that there might be an algorithm in the framework that can be used for that, but couldn't find something.
Also, I suppose this has been asked on SO before, but I came up dry.

任何提示?

推荐答案

如果有人有兴趣,这里就是我想出了:

If anyone is interested, here's what I came up with:

    public static string GetCommonStartingSubString(IList<string> strings)
    {
        if (strings.Count == 0)
            return "";
        if (strings.Count == 1)
            return strings[0];
        int charIdx = 0;
        while (IsCommonChar(strings, charIdx))
            ++charIdx;
        return strings[0].Substring(0, charIdx);
    }
    private static bool IsCommonChar(IList<string> strings, int charIdx)
    {
        if(strings[0].Length <= charIdx)
            return false;
        for (int strIdx = 1; strIdx < strings.Count; ++strIdx)
            if (strings[strIdx].Length <= charIdx 
             || strings[strIdx][charIdx] != strings[0][charIdx])
                return false;
        return true;
    }

这篇关于任何框架的功能帮助找到多个字符串的最长的共同的出发子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆