详细见:leetcode.com/problems/longest-common-prefix/
Java Solution: github
package leetcode;
public class P014_LongestCommonPrefix {
public static void main(String[] args) {
}
/*
* 2 ms
* 65.22%
*/
static class Solution {
public String longestCommonPrefix(String[] strs) {
int minlen = Integer.MAX_VALUE, temp = 0;
if (strs == null || strs.length == 0)
return "";
for (int i = 0; i != strs.length; i ++) {
if (strs[i] == null || (temp = strs[i].length()) == 0)
return "";
minlen = minlen > temp ? temp : minlen;
}
int len = 0;
char c = '\0';
for (; len != minlen; len ++) {
c = strs[0].charAt(len);
for (int i = 1; i != strs.length; i ++) {
if (c != strs[i].charAt(len))
return len == 0 ? "" : strs[0].substring(0, len);
}
}
return len == 0 ? "" : strs[0].substring(0, len);
}
}
}
C Solution: github
/*
url: leetcode.com/problems/longest-common-prefix/
6ms 5.76%
*/
#include <stdlib.h>
#include <string.h>
char* longestCommonPrefix(char** strs, int strsSize) {
int len = 0;
int sign = 1;
int i = 0;
char c = '\0';
char nc = '\0';
char * a = NULL;
if (strs == NULL || strsSize < 1) return "";
while (sign) {
c = *(*(strs + 0) + len);
if (c == '\0') break;
for (i = 1; i < strsSize; i ++) {
nc = *(*(strs + i) + len);
if (nc != c) sign = 0;
}
if (sign) len ++;
}
a = (char *) malloc(sizeof(char) * (len + 1));
*(a + len) = '\0';
for (i = 0; i < len; i ++)
*(a + i) = *(*strs + i);
return a;
}
int main() {
char * sa = "abc";
char * sb = "";
char ** strs = (char **) malloc(sizeof(char *) * 2);
int strsSize = 2;
int i = 0;
char * a = NULL;
*(strs + 0) = sa;
*(strs + 1) = sb;
a = longestCommonPrefix(strs, strsSize);
printf("answer is ");
for (i = 0; i < strlen(a); i ++) {
printf("%c", *(a + i));
}
free(a);
free(strs);
return 0;
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/longest-common-prefix/
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年3月27日
@details: Solution: AC 65ms 24.64%
'''
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
ln = 0 if strs == None else len(strs)
if ln == 0: return ""
sn = (1 << 31) - 1
for i in range(ln):
sn = min(sn, 0 if strs[i] == None else len(strs[i]))
for j in range(sn):
at = True
for i in range(ln):
at &= strs[i][j] == strs[0][j]
if not at:
return strs[0][:j]
return strs[0][:sn]
if __name__ == "__main__":
strs = ["aa", "ab"]
sol = Solution()
print(sol.longestCommonPrefix(strs))