Leetcode学习笔记:#14. Longest Common Prefix
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 “”.
实现:
public String longestCommonPrefix(String[] strs){
if(strs == null || strs.length == 0)
return "";
String pre = strs[0];
int i = 1;
while(i < strs.length){
while(strs[i].indexOf(pre) != 0)
pre = pre.substring(0, pre.length()-1);
i++;
}
return pre;
思路:
设字符串中第一个字符串为prefix,让它与第二个字符串进行比较,如果它存在于第二个字符串中,说明它是第二个的prefix,不是则从后消减字符再进行比较直到它为第二个字符串的prefix。