原题:
Write a function to find the longest common prefix string amongst an array of strings.
即求一组字符串的最长公共前缀
思路:
暴力法,以字符串数组中第一个字符串为基准,遍历第一个字符串,依次将该字符串中的字符与其他字符串相应位置中的字符进行比较。相同则继续,不同则退出,返回上一次循环的结果。
代码(Java):
public class Solution {
public String longestCommonPrefix(String[] strs)
{
if(strs.length == 0)
{
return "";
}
if(strs.length == 1)
{
return strs[0];
}
String prefix = "";
for(int i = 0; i < strs[0].length(); i++) //遍历第一个字符串
{
for(int j = 1; j < strs.length; j++) //遍历整个字符串数组
{
int currentLength = strs[j].length();
//如果当前字符串长度小于i,则无需再进行下去
//如果当前字符与strs[0]相同位置的字符不匹配,也无需进行下去
if(currentLength < i+1 || strs[0].charAt(i)!=strs[j].charAt(i))
{
return prefix;
}
}
prefix = prefix + strs[0].charAt(i);
}
return strs[0];
}
}