Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string “”.
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
思路:两个for循环 ,外层遍历第一个元素,内存遍历数组的每一个元素。一定注意特殊情况,例如数组为空,某些数组某个元素为空等等
package com.wanghao;
public class LongestCommonPrefix {
public static void main(String[] args) {
// TODO Auto-generated method stub
LongestCommonPrefix lCommonPrefix=new LongestCommonPrefix();
String string[]= {"dog","racecar","d"};
System.out.println(lCommonPrefix.longestCommonPrefix(string));
}
public String longestCommonPrefix(String[] strs) {
int num=0;
if (strs == null || strs.length == 0) return "";
for (int i = 1; i < strs[0].length(); i++) {
for (int j = 1; j < strs.length; j++) {
if (!strs[j].startsWith(strs[0].substring(0, i))) {
return strs[0].substring(0, num);
}
}
num++;
}
return strs[0].substring(0, num);
}
}