代码:
class Solution {
public String longestCommonPrefix(String[] strs) { //接收一个字符串数组
if (strs.length == 0) //如果长度为0就返回空
return "";
String prefix = strs[0]; //首先使输入数组的第一个数成为前缀
for (int i = 1; i < strs.length; i++)
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty())
return "";
}
return prefix;
}
}
public class LongestCommonPrefix {
public static void main(String[] args) {
Solution s=new Solution();
String[] a= {"string","str"};
System.out.println(s.longestCommonPrefix(a));
}
}
结果:
str