LeetCode 14. Longest Common Prefix
2016-04-11 11:57
465 查看
Write a function to find the longest common prefix string amongst an array of strings.
Compare one by one, get the common prefix.
Second Round:
To simplify this problem, since we are getting the common prefix for all the input strings, we just need to first sort the input string alphabetically and compare the first and the last to check how much they overlap.
Compare one by one, get the common prefix.
string longestCommonPrefix(vector<string>& strs) { if(strs.size() == 0) return ""; if(strs.size() == 1) return strs[0]; string a = strs[0]; string res; for(int i = 1; i < strs.size(); ++i) { string tmp = ""; int j = 0; int k = 0; while(j < a.size() && k < strs[i].size()) { if(a[j] == strs[i][k]) { tmp= tmp + a[j]; j++; k++; } else break; } a = tmp; res = tmp; } return res; }
Second Round:
To simplify this problem, since we are getting the common prefix for all the input strings, we just need to first sort the input string alphabetically and compare the first and the last to check how much they overlap.
string longestCommonPrefix(vector<string>& strs) { if(strs.size() < 1) return ""; sort(strs.begin(), strs.end()); string front = strs[0]; string end = strs.back(); for(int i = 0; i < front.size() && i < end.size(); ++i) { if(front[i] != end[i]) break; } return front.substr(0, i); }
相关文章推荐
- 【day0411 C++】字符串流istringstream和ostringstream的用法
- ZZULI 1868: UP UP UP!【dp】
- 决策树的数学原理
- vsftp登陆错误530login incorrect及500 oops问题解决
- C++多重继承
- 开源Registry项目Harbor源代码结构解析
- ASP.NET中在后台用C#,往前台插入HTML代码
- 寻梦南非 我心飞翔
- <iOS>cannot be opened because the project file cannot be parsed. Xcode工程文件打不开..
- 3、MongoDB基本管理命令
- JAVA内存溢出,java.lang.OutOfMemoryError: PermGen space
- jquery全屏插件
- LeetCode 235 -Lowest Common Ancestor of a Binary Search Tree ( JAVA )
- k近邻 KNN
- 线性回归 -- 最小二乘法
- SwipeRefreshLayout+RecyclerView实现下拉刷新
- 开始记录我的技术生涯
- 齐次坐标的理解
- 搞清楚CSS单位px、em、rem、vh、vw、vmin、vmax
- Linux有用但不常用的命令