LeetCode - Longest Common Prefix
2013.12.1 23:23
Write a function to find the longest common prefix string amongst an array of strings.
Solution:
For two string s1 and s2, compare the elements from the beginning, when the end or the first mismatch is found, the common prefix is found.
For n strings s[n], perform (n - 1) times such comparings. If the current common prefix is already empty "", then the latter comparison is meaningless and cancelled.
Time complexity is O(n * max(strlen(s[i]))), that means the comparison can be performed at most (n - 1) times, and no single comparison will go longer than the longest string amongst s[n]. Space complexity is O(1).
Actually, if we find out the shortest string s_min amongst s[n], and start the first comparison from the shortest string. We'll gain a time complexity of O(n * min(strlen(s[i]))). Space complexity remains O(1).
Here is an example to show why order of the data matters:
['aaa', ''aaa', 'aaa', 'd']
['d', 'aaa', 'aaa', 'aaa']
The time needed for the two dataset above would be different, since order is different. It's better to put short ones on the front.
Accepted code:
1 // 1RE, 1AC 2 #include <algorithm> 3 using namespace std; 4 5 class Solution { 6 public: 7 string longestCommonPrefix(vector<string> &strs) { 8 // IMPORTANT: Please reset any member data you declared, as 9 // the same Solution instance will be reused for each test case. 10 int n = strs.size(); 11 // 1RE here, didn't consider the case when $strs is empty. 12 if(n <= 0){ 13 return ""; 14 } 15 string res = strs[0]; 16 17 int i; 18 for(i = 1; i < n; ++i){ 19 res = commonPrefix(res, strs[i]); 20 if(res == ""){ 21 break; 22 } 23 } 24 25 return res; 26 } 27 private: 28 string commonPrefix(string s1, string s2) { 29 if(s1.length() > s2.length()){ 30 return commonPrefix(s2, s1); 31 } 32 33 int len1, len2; 34 35 len1 = s1.length(); 36 len2 = s2.length(); 37 int i; 38 for(i = 0; i < len1; ++i){ 39 if(s1[i] != s2[i]){ 40 break; 41 } 42 } 43 44 return s1.substr(0, i); 45 } 46 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)