#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
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.
Top comments (0)