# LeetCode 14：Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

package com.maoxiaomeng;

/**
* @author lihui
* @date 2018/3/26 12:31
*/

public class Solution {
/**
* "lihuia", "lihuib", "lihuiab", "lihuic"
*
* l i h u i a
* l i h u i b
* l i h u i a b
* l i h u i c
* @param strs
* @return
*/
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
for (int i = 0; i < strs[0].length(); i++) {
char c = strs[0].charAt(i);
for (int index = 1; index < strs.length; index++) {
if (i == strs[index].length() || c != strs[index].charAt(i)) {
return strs[0].substring(0, i);
}
}
}
return strs[0];
}
}

Java源码如下

package com.maoxiaomeng;

/**
* @author lihui
* @date 2018/3/26 12:31
*/

public class Solution {
/**
* "lihuia", "lihuib", "lihuiab", "lihuic"
* @param strs
* @return
*/
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
String maxStr = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(maxStr) != 0) {
maxStr = maxStr.substring(0, maxStr.length() - 1);
}
}
return maxStr;
}
}