我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/longest-common-prefix/description/
题目描述:
知识点:字符串
思路一:以第一个字符串为基准找最长公共前缀
对于第一个字符串中的每一个字符,都要在后序的字符串中的相应位置找到相同的字符才将该字符加入到最长公共前缀中,只要在后序字符串中相同位置找到了一个不相同的字符,就直接break跳出循环。
该方法的时间复杂度是O(n * m),其中n为最长公共前缀的长度,m为字符串数组的长度。对于空间复杂度是O(1)级别的。
JAVA代码:
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0 || strs[0].length() == 0) {
return "";
}
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < strs[0].length(); i++) {