Permalink
Branch: master
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
42 lines (33 sloc) 1.08 KB
/*
Descriprion:
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.
Hints:
一个简单的题:找这些字符串最长的公共前缀。
那么,把前缀的初始值赋为第一个字符串,将它与之后的字符串进行比对,截取末尾不同的部分,留下来的字符串即为所求的最长公共前缀。
*/
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(!strs.size()) return "";
string pre = strs[0];
for(int i=1;i<strs.size();i++){
string current = strs[i];
for(int j=0;j<pre.length();j++){
if(pre[j]!=current[j]){
pre = pre.substr(0,j);
break;
}
}
}
cout<<pre;
return pre;
}
};