题目来源:https://leetcode.com/problems/longest-common-prefix/
问题描述
14. Longest Common Prefix
Easy
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.
------------------------------------------------------------
题意
给出一组字符串,求字符串的最大公共前缀。
------------------------------------------------------------
思路
暴力法。
------------------------------------------------------------
代码
class Solution {
public final int INF = (1<<30);
public String longestCommonPrefix(String[] strs) {
int n = strs.length, i = 0, j = 0, minlen = INF, len = 0;
char ch = 0;
if (n == 0)
{
return "";
}
else if (n == 1)
{
return strs[0];
}
StringBuilder sb = new StringBuilder();
for (i=0; i<n; i++)
{
len = strs[i].length();
if (len == 0)
{
return "";
}
minlen = len < minlen ? len : minlen;
}
for (j=0; j<minlen; j++)
{
ch = strs[0].charAt(j);
for (i=1; i<n; i++)
{
if (strs[i].charAt(j) != ch)
{
ch = 0;
break;
}
}
if (ch != 0)
{
sb.append(ch);
}
else
{
break;
}
}
return sb.toString();
}
}