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: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
Python
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
result_str = ""
if strs is not None and len(strs) > 0:
strs.sort()
str_first = strs[0]
str_last = strs[len(strs)-1]
a = 0
for i in str_first:
if i == str_last[a]:
result_str += i
a += 1
else:
return result_str
return result_str
csharp
public class Solution {
public string LongestCommonPrefix(string[] strs) {
string result_str = "";
if (strs != null && strs.Length > 0)
{
Array.Sort(strs);
string str_first = strs[0];
string str_last = strs[strs.Length - 1];
int a = 0;
foreach(var i in str_first)
{
if (string.Equals(i,str_last[a]))
{
result_str += i;
a++;
}
else
{
return result_str;
}
}
}
return result_str;
}
}