java练习(4)
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
public class Solution {
public String longestCommonPrefix(String[] strs) {
// 如果数组为空,直接返回空字符串
if (strs == null || strs.length == 0) {
return "";
}
// 假设第一个字符串为最长公共前缀
String prefix = strs[0];
// 遍历数组中其余的字符串
for (int i = 1; i < strs.length; i++) {
// 当当前字符串不以当前前缀开头时
while (!strs[i].startsWith(prefix)) {
// 缩短前缀,去掉最后一个字符
prefix = prefix.substring(0, prefix.length() - 1);
// 如果前缀为空,说明不存在公共前缀,直接返回空字符串
if (prefix.isEmpty()) {
return "";
}
}
}
return prefix;
}
public static void main(String[] args) {
Solution solution = new Solution();
String[] strs = {"flower", "flow", "flight"};
String result = solution.longestCommonPrefix(strs);
System.out.println("最长公共前缀是: " + result);
}
}