Write a function to find the longest common prefix string amongst an array of strings.
求字符串数组中字符串的最长公共前缀。git
class Solution { public: string longestCommonPrefix(vector<string> &strs) { if(strs.size()<=0)return string(); int idx=0; string res; char c; string s=strs.at(0); //以第一个字串做为比较的基 int n=s.size(),ns=strs.size(); while(idx<n){ c=strs.at(0).at(idx); //获取一个字符 for(int i=0;i<ns;++i){ //循环和其余字串中对应位的字符进行比较 s=strs.at(i); if(idx<s.size()) if(s.at(idx)==c)continue; idx=n; //若是出现不相等或有字符串已结束,则退出循环 break; } if(idx<n){ res.push_back(c); } ++idx; } return res; } };
class Solution { public: string longestCommonPrefix(vector<string> &strs) { if(strs.size()<=0)return string(); int idx=0,base=0; string res; int ns=strs.size(); while(idx<ns){ if(strs.at(idx).size()<strs.at(base).size()) base=idx; ++idx; } idx=0; char c; int n=strs.at(base).size(); while(idx<n){ c=strs.at(base).at(idx); for(int i=0;i<ns;++i){ if(idx<strs.at(i).size()) if(strs.at(i).at(idx)==c)continue; idx=n; break; } if(idx<n){ res.push_back(c); } ++idx; } return res; } };
class Solution { public: string longestCommonPrefix(vector<string> &strs) { if (strs.size() == 0) return ""; string s; for (int i = 0; i < strs[0].length(); i++) { for (int j = 0; j < strs.size() - 1; j++) { if (strs[j + 1].length() <= i || strs[j][i] != strs[j + 1][i]) { return s; } } s.push_back(strs[0][i]); } return s; } };
strs.size()
尽可能放到循环外面来,由于其是一个常量,在内层循环中,若是字串数组很大,就会产生必定的没法消除的效率影响。同时,我更喜欢使用 ++i
代替 i++
,由于这样,能减小一次寄存器存取。也许当数据量少时看不出来这些差距,但代码在手,能优尽优嘛!不过处理了这些,好像就没原来的好看了~~😄class Solution { public: string longestCommonPrefix(vector<string> &strs) { if (strs.size() == 0) return ""; string s; int minlen=strs[0].length(),ns=strs.size(); for(int i=0;i<ns;++i){ minlen<strs[i].length() ? minlen=strs[i].length() :0 ; } ns-=1; for (int i = 0; i < minlen; ++i) { for (int j = 0; j < ns; ++j) { if (strs[j + 1].length() <= i || strs[j][i] != strs[j + 1][i]) { return s; } } s.push_back(strs[0][i]); } return s; } };
同系列:LeetCodesOJhttp://www.cnblogs.com/lomper/tag/LeetCodesOJ/github