LeetCode Online Judge 题目C# 练习 - Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings

 1         public static string LongestCommonPrefix(List<string> strs)

 2         {

 3             if (strs.Count == 0)

 4                 return "";

 5             if (strs.Count == 1)

 6                 return strs[0];

 7 

 8             bool bMatch = true;

 9             int index = 0;

10             string ret = "";

11 

12             while (bMatch)

13             {

14                 foreach (var item in strs)

15                 {

16                     if (index >= item.Length || item[index] != strs[0][index])

17                     {

18                         bMatch = false;

19                         return ret;

20                     }

21                 }

22 

23                 ret += strs[0][index];

24                 index++;

25             }

26 

27             return ret;

28         }

代码分析:

  简单BF。

你可能感兴趣的:(LeetCode)