string longestCommonPrefix(vector<string>& strs)
时间: 2023-12-15 07:04:35 浏览: 70
C++string (含字符串数组)相关用法.pdf
strs) {
if(strs.empty()) return "";
int minStrLen = INT_MAX;
for(auto s:strs) minStrLen = min(minStrLen, (int)s.length());
int l = 0, r = minStrLen-1;
while(l <= r) {
int mid = l + (r-l)/2;
string prefix = strs[0].substr(0, mid+1);
bool flag = true;
for(int i = 1; i < strs.size(); i++) {
if(strs[i].substr(0, mid+1) != prefix) {
flag = false;
break;
}
}
if(flag) l = mid + 1;
else r = mid - 1;
}
return strs[0].substr(0, l);
}
阅读全文