14. 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
输入:strs = [“flower”,“flow”,“flight”]
输出:“fl”
示例 2:
输入:strs = [“dog”,“racecar”,“car”]
输出:""
解释:输入不存在公共前缀。
记录解法
package com.xiang;
/**
* @author snape
* @create 2022-03-13 11:08
*/
public class LongestPublicPrefix {
public static void main(String[] args) {
String[] strs = new String[]{"ab","a"};
if (strs.length == 0 || strs[0].equals("")){
System.out.println("");
}else {
int index = 0;
String prefix = strs[0].substring(0,1);
boolean flag = true;
while (flag){
for (int k = 1; k < strs.length; k++) {
if (index < strs[k].length()){
String sub = strs[k].substring(0, index + 1);
if (!(prefix.equals(sub))){
prefix = strs[0].substring(0,index);
flag = false;
break;
}
}else {
prefix = strs[0].substring(0,index);
flag = false;
break;
}
}
if (flag && index < strs[0].length()-1){
index++;
prefix = strs[0].substring(0,index+1);
}else {
flag = false;
}
}
System.out.println(prefix);
}
}
}
力扣的精选解法
package com.xiang;
/**
* @author snape
* @create 2022-03-13 14:29
*/
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0)
return "";
String ans = strs[0];
for(int i =1;i<strs.length;i++) {
int j=0;
for(;j<ans.length() && j < strs[i].length();j++) {
if(ans.charAt(j) != strs[i].charAt(j))
break;
}
ans = ans.substring(0, j);
if(ans.equals(""))
return ans;
}
return ans;
}
public static void main(String[] args) {
Solution solution = new Solution();
String[] strs = new String[]{"flower","flow","flight"};
String s = solution.longestCommonPrefix(strs);
System.out.println(s);
}
}