DEV Community

Cover image for Longest Common Prefix

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"
Enter fullscreen mode Exit fullscreen mode

Example 2

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


找出陣列中所有元素最長的相同字符並返回,如果沒有相同字符則返回空字串 ""

例如 catcarry 相同的前綴字符為 ca




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])
                return res;

        res += str[i];

    return res;
Enter fullscreen mode Exit fullscreen mode


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
or follow my GitHub
or buy me a coffee ⬇️ I'd appreciate it.


Top comments (0)

We're hiring!

We're Hiring

We're looking for someone who can develop, maintain, and implement our product roadmap and strategy as a Senior Product Manager.

Head here to learn more.