LeetCode14.最长公共前缀
题目
代码
一,
首先可以将字符串数组的前两个字符串比较后得到新的具有公共前缀的新字符串,然后新的字符串继续与下一个字符串比较,不断迭代更新公共前缀直到比较到最后一个字符串就得到了最大公共前缀。
public class Solution
{
public string LongestCommonPrefix(string[] strs)
{
string temp;
if (strs.Length == 0)
temp = "";
else
{
temp = strs[0];
for (int i = 0; i < strs.Length; i++)
temp = TwoCommonPrefix(temp, strs[i]);
}
return temp;
}
public string TwoCommonPrefix(string str1, string str2)
{
int Minlength = Math.Min(str1.Length ,str2.Length );
string newstr = "";
for (int i = 0; i < Minlength; i++)
{
if (str1[i] == str2[i])
newstr = newstr + str1[i];
else
break;
}
return newstr;
}
}
这种方法浪费了很多时间
二,优化
字符串两两比较后得到新的字符串数组,再次两两比较,以此类推,这样会减少运算次数,节省很多时间。
public class Solution
{
public string LongestCommonPrefix(string[] strs)
{
if (strs.Length == 0)
return "";
else if (strs.Length == 1)
return strs[0];
else
return CommonPrefix(strs,0,strs.Length-1);
}
public string CommonPrefix(string[] strs, int start, int end)
{
if (start >= end)
return strs[start];
int mid = start + (end-start)/2;
string str1 = CommonPrefix(strs,start,mid);
string str2 = CommonPrefix(strs,mid+1,end);
return TwoCommonPrefix(str1,str2);
}
public string TwoCommonPrefix(string str1, string str2)
{
int Minlength = Math.Min(str1.Length ,str2.Length );
string newstr = "";
for (int i = 0; i < Minlength; i++)
{
if (str1[i] == str2[i])
newstr = newstr + str1[i];
else
break;
}
return newstr;
}
}
三,水平扫描法
public class Solution
{
public string LongestCommonPrefix(string[] strs)
{
if (strs.Length == 0)
return "";
String temp = strs[0];
for (int i = 1; i < strs.Length; i++)
{
while (strs[i].IndexOf(temp) != 0)
{
temp = temp.Substring(0, temp.Length - 1);
if (temp.Length == 0)
return "";
}
}
return temp;
}
}