public class Solution { public String longestCommonPrefix(String[] strs) { if(strs.length==0)return ""; char[] str=strs[0].toCharArray(); int Min=str.length; for(int i=1;i<strs.length;i++){ char[] s=strs[i].toCharArray(); int j=0; while(j<Min && j<s.length && s[j]==str[j])j++; Min = Min>j?j:Min; } return strs[0].substring(0,Min); } }
char* longestCommonPrefix(char** strs, int strsSize) { char* str=strs[0]; int i,j; if(strsSize==0)return ""; for(i=1;i<strsSize;i++){ j=0; while(str[j] && strs[i][j] && str[j]==strs[i][j])j++; str[j]=0; } return str; }
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if(strs.size()==0)return ""; char* str=(char*)malloc(sizeof(char)*(strs[0].size()+1)); for(int i=0;i<strs[0].size();i++){ str[i]=strs[0][i]; } str[strs[0].size()]=0; for(int i=1;i<strs.size();i++){ int j=0; while(str[j] && strs[i][j] && str[j]==strs[i][j])j++; str[j]=0; } return string(str); } };
class Solution: # @param {string[]} strs # @return {string} def longestCommonPrefix(self, strs): if len(strs)==0:return "" str=strs[0] Min=len(str) for i in range(1,len(strs)): j=0;p=strs[i] while j<Min and j<len(p) and p[j]==str[j]:j+=1 Min = Min if Min<j else j return str[:Min]
LeetCode 14 Longest Common Prefix (C,C++,Java,Python)
原文地址:http://blog.csdn.net/runningtortoises/article/details/45583695