写在前面:
记录LeetCode练习过程,有自己的解决方法,也有借鉴了网上后实现的方法。方法不一定最优秀,但都是实践可用的。一些解释和理解写在程序起始的注释中。若有什么不当之处,欢迎留言交流,大家一起学习。
import java.util.*;
/**
* LeetCode 0014 最长公共前缀
* anthor:MammothKan
* time:2020/5/2
* 问题描述:https://leetcode-cn.com/problems/longest-common-prefix/
* 解题思路:1.直接剔除strs为空的情况,返回“”
* 2.对strs根据字符串长短排序
* 3.选取长度最短的字符串shortestStr
* 4.直接剔除shortestStr为空的情况,返回“”
* 5.遍历shortestStr的字符与strs中其他字符串的字符匹配,一旦出现不匹配的情况便跳出遍历
* 6.返回结果
*/
public class L0014最长公共前缀 {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
Arrays.sort(strs, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.length() < o2.length()) {
return -1;
}
else {
return 1;
}
}
});
if (strs[0] == "") {
return "";
}
int index = 0;
char[] shortestStrs = strs[0].toCharArray();
boolean flag = true;
for (char c : shortestStrs) {
for (int i=1; i<strs.length && flag; i++) {
if (strs[i].charAt(index) != c) {
flag = false;
}
}
if (!flag) {
break;
}
index++;
}
String result = strs[0].substring(0, index);
return result;
}
public static void main(String[] args) {
String[] strs = {"flower","flow","flight"};
System.out.println(new L0014最长公共前缀().longestCommonPrefix(strs));
}
}