leetcode14 最长公共前缀
题目描述
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
算法思路
此处我采用纵向搜索的方法,对字符串数组的每一列进行比较,直到比较长度到达某个最短字符串或者遇到不相同字符。
代码实现
public class Solution {
public static void main(String args[]){
String[] strs = {"qwerewqr", "qwertydafdf","qwertyuiop"};
System.out.println(longestCommonPrefix(strs));
}
public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
int length = strs[0].length(); //第一个字符长度
int count = strs.length; //字符串个数
for (int i = 0; i < length; i++) {
char c = strs[0].charAt(i);
for (int j = 1; j < count; j++) {
//如果当前遍历到的字符位置为该字符串的长度或者字符不相同,返回前面的字符串
if (i == strs[j].length() || strs[j].charAt(i) != c) {
return strs[0].substring(0, i);
}
}
}
return strs[0]; //说明第一个字符串即为最长前缀
}
}