Thursday, February 27, 2014

Longest Common Prefix (Java)

Leetcode

Write a function to find the longest common prefix string amongst an array of strings.


/*
Write a function to find the longest common prefix string amongst an array of strings.
*/
// rewrite at 2/28/2014
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs==null||strs.length==0){
return "";
}
if (strs.length==1){
return strs[0];
}
String str=strs[0];
for (int i=0; i<str.length(); i++){
char c=str.charAt(i);
for (int j=1; j<strs.length; j++){
if (strs[j].length()==i || strs[j].charAt(i)!=c){
return str.substring(0, i);
}
}
}
return str;
}
}
// old version
public class Solution {
public String longestCommonPrefix(String[] strs)
{
if (strs.length==0) return “”;
int index=0;
while (index<strs[0].length())
{
char c=strs[0].charAt(index);
for (int i=1; i<strs.length;i++)
{
// Don’t forget to also check if index out of range of other str in strs beside strs[0]
if (index==strs[0].length()||index==strs[i].length()||strs[i].charAt(index)!=c)
{
return strs[0].substring(0,index);
}
}
index++;
}
return strs[0];
}
}

No comments:

Post a Comment