14. Longest Common Prefix

This commit is contained in:
Пытков Роман
2024-01-30 23:47:49 +03:00
parent 66ea6b80f4
commit 1e43adf29e
5 changed files with 125 additions and 19 deletions

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_14._Longest_Common_Prefix</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,6 @@
// See https://aka.ms/new-console-template for more information
using _14._Longest_Common_Prefix;
string[] strs = ["flower", "flow", "flight"];
Console.WriteLine(new Solution().LongestCommonPrefix(strs));

View File

@@ -0,0 +1,32 @@
using System.Text;
namespace _14._Longest_Common_Prefix;
public class Solution
{
public string LongestCommonPrefix(string[] strs)
{
if (strs.Length == 1)
return strs[0];
StringBuilder sb = new StringBuilder(256);
int maxLen = strs.Select(s => s.Length).Min();
for (int i = 0; i < maxLen; i++)
{
char letter;
if ((letter = strs[0][i]) != strs[1][i])
break;
for (int j = 2; j < strs.Length; j++)
{
if (letter != strs[j][i])
{
maxLen = -1;
break;
}
}
if(maxLen != -1)
sb.Append(letter);
}
return sb.ToString();
}
}