原题:
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:
Input: ["flower","flow","flight"]
Output: "fl"
例2:
Input: ["dog","racecar","car"]
Output: ""
说明: 输入的字符串中没有公共的前缀.
注意:
所有给定的输入都是小写字母a-z.
C++代码:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string prefix = "";
int num=0;
if(strs.empty())return prefix;//对空输入的处理
int shortestlen=strs[0].length();
for(int i=1;i<strs.size();i++)//获取数组中最短字符串的长度
{
if(shortestlen>strs[i].length())shortestlen=strs[i].length();
}
for(num=0;num<shortestlen;num++) //从字符串左侧遍历 以最短字符串长度为基准
{
int right=1;
for(int i=0;i<strs.size();i++)//循环字符串数组 遍历数组中字符串相同位置字母是否相同 如有不同则标志位right置0跳出循环
{
if(strs[0][num]!=strs[i][num]){right=0;break;}
}
if(right==0) break;
}
for(int j=0;j<num;j++)//根据长度num将字符添加到字符串上
{
prefix+=strs[0][j];
}
return prefix;
}
};