Loading
Leetcode / 14. Longest Common Prefix

Pick a programming language:

Here is the source code for the solution to this problem.

public class Solution {
    public string LongestCommonPrefix(string[] strs) {
        string prefix = strs[0];
        
        for (int i = 1; i < strs.Length; i++)
        {
            while (!strs[i].StartsWith(prefix))
            {
                prefix = prefix.Substring(0, prefix.Length - 1);
            }
        }

        return prefix;
    }
}
Did you like the lesson? 😆👍
Consider a donation to support our work: