14. Longest Common Prefix
This commit is contained in:
11
14. Longest Common Prefix/14. Longest Common Prefix.csproj
Normal file
11
14. Longest Common Prefix/14. Longest Common Prefix.csproj
Normal 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>
|
||||
6
14. Longest Common Prefix/Program.cs
Normal file
6
14. Longest Common Prefix/Program.cs
Normal 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));
|
||||
32
14. Longest Common Prefix/Solution.cs
Normal file
32
14. Longest Common Prefix/Solution.cs
Normal 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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user