编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
class Solution { public: string longestCommonPrefix(vector<string>& strs) { string pre = ""; if(strs.size()==0) return ""; int len = strs[0].size(); char c;//= strs[0][0]; int i = 0; while(i < len){ c = strs[0][i]; bool flag = true; for(int j = 1; j < strs.size(); j++){ if(i < strs[j].size()){ if(c != strs[j][i]){ flag = false; } }else { flag = false; break; } } if(flag){ pre += c; i++; }else{ break; } } return pre; } };