FakeStandard

Posted on

# Longest Common Prefix

#14.Longest Common Prefix

### Problem statement

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 1

``````Input: strs = ["flower","flow","flight"]
Output: "fl"
``````

Example 2

``````Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
``````

### Solution

``````public string LongestCommonPrefix(string[] strs)
{
if (strs.Length == 0) return null;

string res = string.Empty;
string str = strs[0];

foreach (var s in strs)
{
if (s.Length < str.Length)
str = s;
}

int len = strs.Length;

for (int i = 0; i < str.Length; i++)
{
for (int j = 0; j < len; j++)
{
if (str[i] == strs[j][i])
continue;
else
return res;
}

res += str[i];
}

return res;
}
``````

### Reference

LeetCode Solution

GitHub Repository

Thanks for reading the article 🌷 🌻 🌼

If you like it, please don't hesitate to click heart button ❤️
or click like on my Leetcode solution