题目描述:
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入: [“flower”,“flow”,“flight”]
输出: “fl”
示例 2:
输入: [“dog”,“racecar”,“car”]
输出: “”
解释: 输入不存在公共前缀。
思想:
- 直接遍历第一个字符串,然后依次取出字符与后续字符串的相应位置进行比较即可,
- 在遍历的过程中,如果某一个字符串没有了,说明其为最短的单词,直接返回即可 。
- 因为共同前缀的和长度不能大于最短的单词。
public class test1 {
public static String longestCommonPrefix(String[] strs) {
//处理特殊情况
if(strs == null ||strs.length == 0) return "";
String res = new String();
//遍历第一个字符串中的所有字符
for(int j = 0; j < strs[0].length(); j++) {
//获取第一个字符串的单个字符
char c = strs[0].charAt(j);
//遍历剩下的字符串
for(int i = 1; i < strs.length; i++) {
//如果j>=strs[i].length()说明当前串strs[i]最短,此时的公共串就是最长公共串
if(j >= strs[i].length() || strs[i].charAt(j) != c) {
//直接返回
return res;
}
}
//公共字符拼接
res += Character.toString(c);
}
return res;
}
public static void main(String[] args) {
String [] strs = {"flower","flow","flight"};
String result = longestCommonPrefix(strs);
System.out.println(result);
}
}