-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongestCommonPrefix.cs
37 lines (28 loc) · 1003 Bytes
/
LongestCommonPrefix.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
32
33
34
35
36
37
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCodeSolutions
{
// Source: https://leetcode.com/problems/longest-common-prefix/
// Author: Jalal Shabo
// Date : 11/28/2023
// Time Complexity: O(n Log n) OrderBy LinQ method longest time complexity foreach statement is O(n*m)
// Space Complexity: O(n) length of longest prefix
public static class LongestCommonPrefix
{
public static string LongestCommonPrefixSolution(string[] strs){
int index = 0;
StringBuilder longestPrefix = new StringBuilder();
string shortest = strs.OrderBy(x => x.Length).First();
foreach (char ch in shortest)
{
if (strs.Any(s => s[index] != ch)) break;
longestPrefix.Append(ch);
index++;
}
return longestPrefix.ToString();
}
}
}