14 Longest Common Prefix

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

 

public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}

String longcommon = strs[0];
for (int i = 1; i < strs.length; i++) {
if (longcommon.length() > strs[i].length()) {
longcommon = longcommon.substring(0, strs[i].length());
}
for (int j = 0; j < strs[i].length(); j++) {
if (j >= longcommon.length()) {
break;
}

if (longcommon.charAt(j) != strs[i].charAt(j)) {
longcommon = longcommon.substring(0, j);
}
}
}

return longcommon;
}
}

posted @ 2017-05-12 13:03  阿宝果果  阅读(105)  评论(0)    收藏  举报