公衆號:愛寫bugjava
Write a function to find the longest common prefix string amongst an array of strings.python
If there is no common prefix, return an empty string ""
.數組
編寫一個函數來查找字符串數組中的最長公共前綴。app
若是不存在公共前綴,返回空字符串 ""
。函數
Example 1:ui
Input: ["flower","flow","flight"] Output: "fl"
Example 2:spa
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:.net
All given inputs are in lowercase letters a-z
.code
說明:component
全部輸入只包含小寫字母 a-z
。
很簡單又很經典的一道題,個人思路起先是 把第字符串組第一個字符串轉爲char型。利用StringBuilder逐一累加相同字符。因爲字符串長度不一,能夠先遍歷找出最小長度字符串,這裏我選擇拋錯的形式,減小一次遍歷。
代碼:
class Solution { public String longestCommonPrefix(String[] strs) { int strLen=strs.length; if(strLen==0) return "";//空字符串組返回"" char[] temp=strs[0].toCharArray(); StringBuilder str = new StringBuilder(); for (int i=0;i<strs[0].length();i++){//以第一個字符串長度開始比較 for (int j=1;j<strLen;j++){ try { if(temp[i]!=strs[j].charAt(i)){ return str.toString(); } }catch (IndexOutOfBoundsException e){//拋出錯誤,這裏錯誤是指索引超出字符串長度 return strs[j]; } } str.append(temp[i]); } return strs[0]; } }
後面想到Java有 subString()
方法,可指定長度截取字符串,無需轉爲 char[]
型,可是在 Leetcode 提交時反而不如上面這種方式運算快,這也說明了Java不支持運算符重載,使用 substring()
每次新建一個String字符串,效率並不高。
最後看到一個方法,大體思路是找到最小長度字符串,從大到小截取字符串,既然用到 subString()
方法,不如就從後向前,由於題目是找出最長公衆前綴,從大到小效率很高。具體請看:
public class Solution { public String longestCommonPrefix(String[] strs) { if(strs.length==0) return ""; int min=Integer.MAX_VALUE; String minStr=""; for(int i=0;i<strs.length;i++){//找出最小長度字符串 if(min>strs[i].length()){ minStr=strs[i]; min=strs[i].length(); } } if(min==0) return ""; for(int i=min;i>=0;i--){//最小長度字符串從長到短截取 String standard=minStr.substring(0, i); int j=0; for(j=0;j<strs.length;j++){ if(strs[j].substring(0, i).equals(standard)) continue; else break; } if(j==strs.length) return standard; } return ""; } }
原代碼連接: http://www.javashuo.com/article/p-vdxjqbyf-bx.html
再次投機取巧,os.path 封裝函數 commonprefix()
一步到位。
代碼:
class Solution(object): def longestCommonPrefix(self, strs): import os return os.path.commonprefix(strs)
其實該函數是利用ASCll碼比較的特性來編寫的,源碼:
def commonprefix(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' # Some people pass in a list of pathname parts to operate in an OS-agnostic # fashion; don't try to translate in that case as that's an abuse of the # API and they are already doing what they need to be OS-agnostic and so # they most likely won't be using an os.PathLike object in the sublists. if not isinstance(m[0], (list, tuple)): m = tuple(map(os.fspath, m)) s1 = min(m) s2 = max(m) for i, c in enumerate(s1)://枚舉獲得s1的每個字符及其索引 if c != s2[i]: return s1[:i] return s1
儘管如此,py3這段代碼的執行速度依然遠比Java慢的多。
**注:**ASCll碼比較大小並不是是按照全部字符的ASCll累加之和比較,是從一個字符串第一個字符開始比較大小,若是不相同直接得出大小結果,後面的字符不在比較。