题目
编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 “”。
说明: 所有输入只包含小写字母 a-z。
题解
- 字符串数组长度为0时,则公共前缀为空,直接返回空字符串; 先令公共前缀preStr的值为字符串数组中的第一个字符串;
- 然后用两个for循环,第一个for循环遍历给定的字符串数组,从第二个字符串开始比较;
- 第二个for循环遍历当前字符串的每一个字母,两两比较查找出两个字符串的公共前缀,得到结果重新赋值给preStr,继续往下查找,最终结果即为整个字符串数组的最长公共前缀。
代码
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0)
return "";
String preStr = strs[0];
for (int i = 1; i < strs.length; i++) {
int j = 0;
for (j = 0; j < preStr.length() && j < strs[i].length(); j++) {
if (preStr.charAt(j) != strs[i].charAt(j))
break;
}
preStr = preStr.substring(0, j);
}
return preStr;
}
}