Finding "Longest Common Prefix" string amongst an array of strings | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public string[] strings = { "flower", "flow", "flight" };

    void Start()
    {
        Debug.Log("LCF => "+LongestCommonPrefix(strings));
    }

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

        string 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 (string.IsNullOrEmpty(prefix))
                    return "";
            }
        }
        return prefix;
    }
}