2

#yyds干货盘点# leetcode算法题:最长公共前缀

 1 year ago
source link: https://blog.51cto.com/u_13321676/5570072
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# leetcode算法题:最长公共前缀

原创

灰太狼_cxh 2022-08-12 10:08:25 博主文章分类:leetcode ©著作权

文章标签 代码实现 i++ 最长公共前缀 文章分类 Java 编程语言 阅读数161

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。

输入:strs = ["flower","flow","flight"]

输出:"fl"

输入:strs = ["dog","racecar","car"]

输出:""

解释:输入不存在公共前缀。

代码实现:

class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
int minLength = Integer.MAX_VALUE;
for (String str : strs) {
minLength = Math.min(minLength, str.length());
}
int low = 0, high = minLength;
while (low < high) {
int mid = (high - low + 1) / 2 + low;
if (isCommonPrefix(strs, mid)) {
low = mid;
} else {
high = mid - 1;
}
}
return strs[0].substring(0, low);
}

public boolean isCommonPrefix(String[] strs, int length) {
String str0 = strs[0].substring(0, length);
int count = strs.length;
for (int i = 1; i < count; i++) {
String str = strs[i];
for (int j = 0; j < length; j++) {
if (str0.charAt(j) != str.charAt(j)) {
return false;
}
}
}
return true;
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK