最长公共前缀Java代码
时间: 2024-06-03 19:09:40 浏览: 16
以下是求解最长公共前缀的Java代码:
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].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) {
return "";
}
}
}
return prefix;
}
请问还有其他问题需要我回答吗?
相关问题
Java编写最长公共前缀的代码
当然可以!以下是一个用 Java 编写的找到最长公共前缀的代码示例:
```java
public class LongestCommonPrefix {
public static String findLongestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 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 static void main(String[] args) {
String[] strs = {"flower", "flow", "flight"};
String longestCommonPrefix = findLongestCommonPrefix(strs);
System.out.println("Longest Common Prefix: " + longestCommonPrefix);
}
}
```
以上代码中,`findLongestCommonPrefix()` 方法接受一个字符串数组作为参数,然后通过逐个比较字符串的字符来找到最长公共前缀。在 `main()` 方法中,我们使用示例数组 `strs` 来测试该方法,并打印输出最长公共前缀。
希望以上代码能够解决您的问题!如果有任何疑问,请随时提出。
java 最长公共前缀
Java中求最长公共前缀可以使用水平扫描法。具体步骤如下:
1. 首先,将第一个字符串作为最长公共前缀的初始值。
2. 从第二个字符串开始,依次与最长公共前缀进行比较。
3. 如果当前字符串不以最长公共前缀开头,则将最长公共前缀的长度减1,直到最长公共前缀为空或者当前字符串以最长公共前缀开头。
4. 重复步骤2和步骤3,直到遍历完所有的字符串。
以下是Java代码示例:
```java
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].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) {
return "";
}
}
}
return prefix;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)