FakeStandard

Posted on

Longest Common Prefix

#14.Longest Common Prefix

Problem statement

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string `""`.

Example 1

``````Input: strs = ["flower","flow","flight"]
Output: "fl"
``````

Example 2

``````Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
``````

Explanation

ζΎεΊι£εδΈ­ζζεη΄ ζι·ηηΈεε­η¬¦δΈ¦θΏεοΌε¦ζζ²ζηΈεε­η¬¦εθΏεη©Ίε­δΈ² `""`γ

δΎε¦ `cat` ε `carry` ηΈεηεηΆ΄ε­η¬¦ηΊ `ca`

Solution

η¨ιθΏ΄ειδΈζ―ε°οΌη¬¬δΈε±€ιζ­·εη΄ ι·εΊ¦οΌη¬¬δΊε±€ειζ­·ι£εε§ζζεη΄ γ

δ½ζ―ζΎε°ι£εε§εη΄ ζοΌδΈε―δ½Ώη¨θΆεΊεη΄ ι·εΊ¦ηη΄’εΌοΌζεζΎε°ι£εε§ζη­ι·εΊ¦ηεη΄ οΌεδ»₯ζ­€ι·εΊ¦δ½ηΊη¬¬δΈε±€θΏ΄εηδΈ­ζ­’εΌγ

``````public string LongestCommonPrefix(string[] strs)
{
if (strs.Length == 0) return null;

string res = string.Empty;
string str = strs[0];

foreach (var s in strs)
{
if (s.Length < str.Length)
str = s;
}

int len = strs.Length;

for (int i = 0; i < str.Length; i++)
{
for (int j = 0; j < len; j++)
{
if (str[i] == strs[j][i])
continue;
else
return res;
}

res += str[i];
}

return res;
}
``````

Reference

LeetCode Solution

GitHub Repository

Thanks for reading the article π· π» πΌ

If you like it, please don't hesitate to click heart button β€οΈ
or click like on my Leetcode solution
or follow my GitHub β­
or buy me a coffee β¬οΈ I'd appreciate it.