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


Solution.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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;
    }
}