1. 程式人生 > 其它 >java 遍歷字串_最長公共字串字首

java 遍歷字串_最長公共字串字首

技術標籤:java 遍歷字串java遍歷字串postgresql 遍歷字串陣列

最長公共字首

Question:編寫一個函式來查詢字串陣列中的最長公共字首。如果不存在公共字首,返回空字串""

示例1:

IN:["flower","flow","flight"]
OUT:"fl"

示例2:

IN:["dog","racecar","car"]
OUT:""

說明:所有輸入只包含小寫字母a-z

思路

給定一個字串陣列,兩兩比較公共字串字首,記錄當前公共字串字首,如果新的字串字首較短,則更新。遍歷整個陣列之後,得到的即是最短的公共字串字首。如給定 ["flower","flow","flight","float"]
首先對比"flower"和"flow",找到最短字首為 "flow",接著對比"flow"和"flight",得到最短字首為 "fl",對比 "flow和fl","fl"更短,則最短字首更新為"fl"。接著對比"flight"和"float",得到最短字首 "fl",則最短字首為 "fl"

原始碼(Java,goldsunC版):

classSolution{
publicStringlongestCommonPrefix(String[]strs){
if(strs==null||strs.length==0){
return"";
}
Stringnowstr=strs[0];
for(inti=0;i1;i++){if(nowstr.length()>pubstring(strs[i],strs[i+1]).length()){
nowstr=pubstring(strs[i],strs[i+1]);
}if(nowstr.length()==0)return"";
}returnnowstr;
}publicStringpubstring(Stringa,Stringb){intminlength;
Stringnowstr="";
minlength=Math.min(a.length(),b.length());for(intindex=0;indexif(a.charAt(index)==b.charAt(index)){
nowstr=nowstr+a.charAt(index);
}else{returnnowstr;
}
}returnnowstr;
}
}

原始碼(Python,goldsunC版):

classSolution:
deflongestCommonPrefix(self,strs:List[str])->str:
ifnotstrs:
return""
nowstr=strs[0]
foriinrange(len(strs)-1):
iflen(nowstr)>len(self.pubstr(strs[i],strs[i+1])):
nowstr=self.pubstr(strs[i],strs[i+1])
returnnowstr
defpubstr(self,a,b):
nowstr=''
c=min(len(a),len(b))
foriinrange(c):
ifa[i]==b[i]:
nowstr=nowstr+a[i]
else:
returnnowstr
returnnowstr

這是我寫的程式碼,兩種原始碼的思路一樣。

官方思路

總共四種: 橫向掃描縱向掃描分治二分查詢

橫向掃描:

依次遍歷字串陣列中的每個字串,對於每個遍歷到的字串,更新最長公共字首,當遍歷完所有的字串以後,即可得到字串陣列中的最長公共字首。如給定 ["flower","flight","float","flow"]首先對比"flower"和"flight",找到最短字首為 "fl",接著對比"fl"和"float",得到最短字首為 "fl",接著對比"fl"和"flow",則最短字首為 "fl"

原始碼(Java,官方版):

classSolution{
publicStringlongestCommonPrefix(String[]strs){
if(strs==null||strs.length==0){
return"";
}
Stringprefix=strs[0];
intcount=strs.length;
for(inti=1;iprefix=longestCommonPrefix(prefix,strs[i]);
if(prefix.length()==0){
break;
}
}
returnprefix;
}
publicStringlongestCommonPrefix(Stringstr1,Stringstr2){
intlength=Math.min(str1.length(),str2.length());
intindex=0;
while(indexindex++;
}
returnstr1.substring(0,index);
}
}
/**
作者:LeetCode-Solution
連結:https://leetcode-cn.com/problems/longest-common-prefix/solution/zui-chang-gong-gong-qian-zhui-by-leetcode-solution/
*/

原始碼(Python,官方版):

classSolution:

•end•

走在路上

goldsunC

d1ca4f349402e9e78f904d1e83630cd9.png