BM84. 最长公共前缀
描述
示例1
输入:
["abca","abc","abca","abc","abcc"]
输出:
"abc"
示例2
输入:
["abc"]
输出:
"abc"
C++ 解法, 执行用时: 2ms, 内存消耗: 396KB, 提交时间: 2021-08-01
class Solution { public: /** * * @param strs string字符串vector * @return string字符串 */ string longestCommonPrefix(vector<string>& strs) { // write code here if(strs.size()==0) return ""; string str=strs[0]; for(int i=1;i<strs.size();i++) { if(strs[i].size()==0) return ""; int x=str.size(),y=strs[i].size(); for(int j=0;j<=min(x,y);j++) { if(str[j]!=strs[i][j]){ str=str.substr(0,j); break; } } } return str; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 416KB, 提交时间: 2021-07-26
class Solution { public: /** * * @param strs string字符串vector * @return string字符串 */ string longestCommonPrefix(vector<string>& strs) { // write code here if(strs.empty()) return ""; string res=strs[0]; for(auto &str:strs){ int i=res.size()-1; while(i>=0){ if(str[i]!=res[i]){ res.pop_back(); } i--; } } return res; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 424KB, 提交时间: 2021-07-27
class Solution { public: /** * * @param strs string字符串vector * @return string字符串 */ string longestCommonPrefix(vector<string>& strs) { // write code here if(strs.empty())return ""; sort(strs.begin(),strs.end()); string f=strs.front(),b=strs.back(); int idx=0,n=min(f.size(),b.size()); while(idx<n&&f[idx]==b[idx])idx++; return f.substr(0,idx); } };
C++ 解法, 执行用时: 2ms, 内存消耗: 424KB, 提交时间: 2021-07-25
class Solution { public: /** * * @param strs string字符串vector * @return string字符串 */ string getcommonprefix(string &s1,string &s2) { int index=0; int length=min(s1.length(),s2.length()); while(index<length && s1[index]==s2[index]) { index++; } return s1.substr(0,index); } string longestCommonPrefix(vector<string>& strs) { // write code here if(!strs.size()) return ""; string prefix=strs[0]; for(int i=1;i<strs.size();i++) { prefix=getcommonprefix(prefix, strs[i]); } return prefix; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 428KB, 提交时间: 2021-07-28
class Solution { public: /** * * @param strs string字符串vector * @return string字符串 */ string longestCommonPrefix(vector<string>& strs) { // write code here string res; if(strs.empty()) return res; for(int i=0;;i++){ if(i>=strs[0].size()) return res; char c=strs[0][i]; for(auto&str:strs) if(str.size()<=i||str[i] !=c) return res; res+=c; } return res; } };