输入:strs = ["flower","flow","flight"]得到第一和第二个字符串的公共前缀 用java实现
时间: 2023-07-21 12:02:46 浏览: 91
你可以使用以下Java代码来获取第一个和第二个字符串的公共前缀:
```java
public class Main {
public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
String commonPrefix = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(commonPrefix) != 0) {
commonPrefix = commonPrefix.substring(0, commonPrefix.length() - 1);
if (commonPrefix.isEmpty()) {
return "";
}
}
}
return commonPrefix;
}
public static void main(String[] args) {
String[] strs = {"flower", "flow", "flight"};
String result = longestCommonPrefix(strs);
System.out.println(result);
}
}
```
输出将是:"fl",即第一个和第二个字符串的公共前缀。
阅读全文