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.
翻译
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入: [“flower”,“flow”,“flight”]
输出: “fl”
示例 2:
输入: [“dog”,“racecar”,“car”]
输出: “”
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。
分析
逐个遍历。
c++实现
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() == 0)
return "";
int least = INT_MAX;
bool chongtu = false;
string res = "";
for (int i = 0; i < strs.size(); i++)
least = least <= strs[i].length() ? least : strs[i].length();
OUT:
for (int i = 0; i < least; i++)
{
for (int j = 0; j+1 < strs.size(); j++)
{
if (strs[j][i] != strs[j+1][i])
chongtu = true;
if (chongtu)
break;
}
if (chongtu)
break;
res += strs[0][i];
}
return res;
}
};