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