In this article, we will see the longest common prefix in C#
Problem Description
Write a function to find the longest common prefix string amongst all the arrays of strings in C#.
If there is no any common prefix then return an empty string "".
The solution to finding the Longest Common Prefix
Input Example
Example 1
Let the set of strings be { "flower", "flight", "fly", "flow" };
The longest common prefix here is "fl"
Example 2
Let the set of strings be {"dot", "dog", "donkey", "door", "cat" } there is no common prefix here so the longest common prefix is "", which means, an empty string.
Since there is no common prefix at all.
To find the longest common prefix of a given set of strings in C#, you can use the following algorithm:
- Initialize a variable prefix to an empty string.
- If the input array is empty, return the empty string.
- Sort the input array in lexicographic order.
- Iterate over the characters in the first string in the sorted array.
- For each character, compare it to the corresponding character in the other strings in the array. If any of the characters don't match, return the current prefix.
- If all the characters match, append the current character to the prefix.
- Return the prefix.
Here is the C# code that implements this algorithm:
You can call this method with an array of strings as an argument, like this:
This code will output "fl", which is the longest common prefix of the input strings "flower", "flight", "flow", and "flight".
Output
-----------------------------------------------------