How to find the longest common prefix of all the words in a string with C#

1 Answer

0 votes
using System;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
    static string LongestCommonPrefix(string input) {
        if (string.IsNullOrWhiteSpace(input))
            return "";

        // Split by non‑word characters (same as Java's split("\\W+"))
        var words = Regex.Split(input.ToLower(), "\\W+")
                         .Where(w => w.Length > 0)
                         .ToArray();

        if (words.Length == 0)
            return "";

        string prefix = words[0];

        for (int i = 1; i < words.Length; i++) {
            while (!words[i].StartsWith(prefix)) {
                prefix = prefix.Substring(0, prefix.Length - 1);
                if (prefix.Length == 0)
                    return "";
            }
        }

        return prefix;
    }

    static void Main()
    {
        string s1 = "The lowly inhabitants of the lowland were surprised to see the lower branches.";
        Console.WriteLine($"LCP: '{LongestCommonPrefix(s1)}'");

        string s2 = "unclear, uncertain, unexpected";
        Console.WriteLine($"LCP: '{LongestCommonPrefix(s2)}'");
    }
}



/*
run:

LCP: ''
LCP: 'un'

*/

 



answered Mar 11 by avibootz

Related questions

...