争取每周做五个LeedCode题,定期更新,难度由简到难
Title: Longest Common Prefix
Description:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""..
Example:
Input: ["flower","flow","flight"]
Output: "fl"
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Difficulty:
Easy
Implement Programming Language:
C#
Answer:
这个问题LeetCode给了一个很全的Solution,5个Approach,可以看一下原文,这里提示一下,要选取的是都相同的最长的前缀,不是最长的相同的字符串,这里就贴一个解法的代码,后续有空,把思路翻译一下解释一下。
public string longestCommonPrefix(string[] strs)
{
if (strs.Length == 0) return "";
var prefix = strs[0];
for (int i = 1; i < strs.Length; i++)
while (strs[i].IndexOf(prefix) != 0)
{
prefix = prefix.Substring(0, prefix.Length - 1);
if (prefix == "") return "";
}
return prefix;
}