/**
*
* Write a function to find the longest common prefix string amongst an array of strings.
*
*/
public class LongestCommonPrefix {
static String longestCommonPrefix(String[] strs) {
if (strs.length == 0) return "";
String compareStr = strs[0];
int commonIndex = strs[0].length() - 1;
for (int i = 1; i < strs.length; i++) {
if(strs[i].length() == 0) return "";
for (int j = 0; j < strs[i].length() && j <= commonIndex; j++) {
if (compareStr.charAt(j) != strs[i].charAt(j)) {
commonIndex = j - 1;
break;
}
if (j == strs[i].length() - 1) commonIndex = j;
}
}
return compareStr.substring(0, commonIndex + 1);
}
public static void main(String[] args) {
String[] strs = {"abcd", "abcd", "abcd", "abcdc"};
System.out.println(longestCommonPrefix(strs));
String[] strs1 = {""};
System.out.println(longestCommonPrefix(strs1));
}
}
[LeetCode Java] 14 Longest Common Prefix
最新推荐文章于 2021-12-07 10:21:58 发布