質問:文字列の配列の中で最も長い共通接頭文字列を見つける関数を書く。Leetcode - 最も長い共通プレフィックス - ランタイムがソリューションに比べて遅いのはなぜですか?
これはleetcodeからの簡単な質問です。以下は私のVSです。解決策の答え。問題は、私の答えがランタイムスピードの1.17%を上回り、ソリューションが79.65%を打つということです。 なぜコードが遅いのですか?
私たちのコードは、最初の共通文字列を操作し始めるまではほとんど同じです。これは、Stringクラスのindexofとsubstring関数を呼び出すことでこれを行い、私が定義したfindCommon関数を使用してそれを行います。
ソリューション:
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) return "";
String pre = strs[0];
int i = 1;
while(i < strs.length){
while(strs[i].indexOf(pre) != 0)
pre = pre.substring(0,pre.length()-1);
i++;
}
return pre;
}
これは私です:私の意見では
public static String longestCommonPrefix(String[] strs){
if(strs == null || strs.length == 0)
return "";
String result = strs[0];
for(int index = 1; index < strs.length; index++)
result = findCommon(result, strs[index]);
return result;
}
public static String findCommon(String a, String b){
String common = "";
for(int index = 0; index < Math.min(a.length(), b.length()); index++)
{
if(a.charAt(index) == b.charAt(index))
common += a.charAt(index);
else
break;
}
return common;
}
関数は文字列ライブラリで定義されているので、ソリューションのコードは単純に見えます。しかし、それは彼らが存在しないことを意味しません。