题解 | #最长公共前缀#
最长公共前缀
https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
#include <algorithm> class Solution { public: string longestCommonPrefix(vector<string>& strs) { if(strs.empty()) return ""; string res = strs[0]; //模板 int mx = res.size(); for (int i = 1; i < strs.size(); i++) { int j, len = strs[i].size(); mx = min(mx, len); for (j = 0; j < mx; j++) { if (res[j] != strs[i][j]) break; //记录最长公共前缀位置j } res.erase(res.begin() + j, res.end()); //更新最长公共前缀 } return res; } };