{ "type": "code_options", "author": "csdn.net", "source": "solution.md", "exercise_id": "5ac00270616644e09618039fd1ded545", "keywords": "字符串", "title": "最长公共前缀", "desc": [ { "content": "\n

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 \"\"

 

示例 1:

输入:strs = [\"flower\",\"flow\",\"flight\"]
输出:
\"fl\"

示例 2:

输入:strs = [\"dog\",\"racecar\",\"car\"]
输出:
\"\"
解释:
输入不存在公共前缀。

 

提示:

", "language": "markdown" } ], "answer": [ { "content": "", "language": "cpp" } ], "prepared": [ [ { "content": "", "language": "cpp" } ], [ { "content": "", "language": "cpp" } ], [ { "content": "", "language": "cpp" } ] ], "template": { "content": "class Solution\n{\npublic:\n\tstring longestCommonPrefix(vector &strs)\n\t{\n\t\tstring lcp;\n\t\tif (strs.size() == 0)\n\t\t\treturn lcp;\n\t\tint min_len = INT_MAX;\n\t\tint min_idx = 0;\n\t\tfor (int i = 0; i < strs.size(); ++i)\n\t\t{\n\t\t\tauto &s = strs[i];\n\t\t\tif (s.size() < min_len)\n\t\t\t{\n\t\t\t\tmin_len = s.size();\n\t\t\t\tmin_idx = i;\n\t\t\t}\n\t\t}\n\t\tauto &smin = strs[min_idx];\n\t\tfor (int i = 0; i < min_len; ++i)\n\t\t{\n\t\t\tchar c = smin[i];\n\t\t\tint j;\n\t\t\tfor (j = 0; j < strs.size(); ++j)\n\t\t\t{\n\t\t\t\tauto &cs = strs[j];\n\t\t\t\tif (c != cs[i])\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (j == strs.size())\n\t\t\t\tlcp += c;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t\treturn lcp;\n\t}\n};", "language": "cpp" }, "node_id": "dailycode-a56baed6a62a46eebdc8c20b2ca8fa0f", "license": "csdn.net", "created_at": 1637894160, "topic_link": "https://bbs.csdn.net/topics/600469918" }