您的位置:首页 > 编程语言 > Java开发

Leetcode刷题记——14. Longest Common Prefix(最长公共前缀)

2016-10-17 17:09 337 查看
一、题目叙述:

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

Subscribe to see which companies asked this question

二、解题思路:

非常简单的题,但我交了四次。。。说思路。

1、首先比较前两个字符串,从第一个字符挨个比较,相等加入公共前缀字符串变量,不相等跳出。

2、其余字符串数组的字符串挨个与第一步得到的字符串变量比较,从第一个字符挨个比较,不相等,减去不相等之后的部分。

注意:

a.注意考虑字符串数组为空即一个字符串也没有的情况

b.注意字符串数组只有一个字符串,那么最长的公共前缀就是这个字符串。

c.这是我自己写的时候的疏漏,当把第一步得到的公共前缀与后面的字符串比较时,若后面的字符串比前面得到的公共前缀还短,那么先把记录公共前缀的字符串裁剪的跟当前字符串数组的字符串长度相等,再比较。

三、源源源码:

public class Solution
{
public String longestCommonPrefix(String[] strs)
{

String a = "";
if (strs.length == 1) return strs[0];
if (strs.length == 0) return "";
for (int i = 0; i < Math.min(strs[0].length(), strs[1].length()); i++)
{
if (strs[0].charAt(i) == strs[1].charAt(i))
{
a = a + strs[0].charAt(i) + "";
}
else
break;
}
for (int i = 2; i < strs.length; i ++)
{
if (strs[i].length() < a.length()) a = a.substring( 0, strs[i].length());
for (int j = 0; j < Math.min(strs[i].length(), a.length()); j ++)
{
if (strs[i].charAt(j) != a.charAt(j))
{
// if (j == 0) return "";
a = a.substring(0, j);
break;
}
}
}
return a;
}
public static void main(String args[])
{
String[] tr = new String[3];
tr[0] = "a";
tr[1] = "a";
tr[2] = "";
Solution a = new Solution();
System.out.println(a.longestCommonPrefix(tr));

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java