# Leetcode 14. 最长公共前缀

## 欢迎通过语雀主页查看 Leetcode 14. 最长公共前缀

#### 思路

##### 思路1：两两取公共前缀

###### 代码
``````public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0];
}

for (String str : strs) {
}
}

// 取出2个字符串

// 获取公共前缀
StringBuilder commonPrefix = new StringBuilder();
for (int i = 0; i < s1.length() && i < s2.length(); i++) {
if (s1.charAt(i) == s2.charAt(i)) {
commonPrefix.append(s1.charAt(i));
} else {
break;
}
}

// 公共前缀加入数组
}

}``````

##### 思路2：排序

###### 代码
``````public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0];
}

// 排序
Arrays.sort(strs);
String s1 = strs[0];
String s2 = strs[strs.length - 1];
StringBuilder commonPrefix = new StringBuilder();
for (int i = 0; i < s1.length() && i < s2.length(); i++) {
if (s1.charAt(i) == s2.charAt(i)) {
commonPrefix.append(s1.charAt(i));
} else {
break;
}
}
return commonPrefix.toString();
}``````

244 声望
3 粉丝
0 条评论