c# LeetCode 14. 最长公共前缀 (string)
原题:https://leetcode-cn.com/problems/longest-common-prefix/
拿到第一个字符串,依次比较,逐渐削减自身。直到所有的字符都比较完成。
public class Solution {
public string LongestCommonPrefix(string[] strs) {
if (strs.Length == 0) return "";
String prefix = strs[0];
for (int i = 0; i < strs.Length; i++)
{
while (strs[i].IndexOf(prefix)!=0)
{
prefix = prefix.Substring(0, prefix.Length - 1);
if (string.IsNullOrWhiteSpace(prefix))
{
return "";
}
}
}
return prefix;
}
}