leetcode_c++:Longest Common Prefix(014)
2016-08-05 18:38
381 查看
Write a function to find the longest common prefix string amongst an array of strings.
求多个字串的最长前缀
求多个字串的最长前缀
算法
O(n^2)class Solution { public: string longestCommonPrefix(vector<string> &strs) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if (strs.size() == 0) return ""; string prefix = strs[0]; for (int i = 1; i < strs.size(); ++i) { if (prefix.length() == 0 || strs[i].length() == 0) return ""; int len = prefix.length() < strs[i].length() ? prefix.length() : strs[i].length(); int j; for (j = 0; j < len; ++j) { if (prefix[j] != strs[i][j]) break; } prefix = prefix.substr(0,j); } return prefix; } };
相关文章推荐
- c++ 和 c 中函数和变量的互用
- C语言学习7
- C++: read access data using ADOX.DLL and System::Data::OleDb
- NOIP2006普及组复赛试题 1.明明的随机数(桶排序,冒泡排序,快速排序)
- c++中set特性和如果索引类set容器的元素
- Cpp环境【Vijos1037】【CQYZos1391】搭建双塔
- kmp的c++代码
- constexpr-C++11
- c/c++ 使用比long long还大的类型
- C++总结之虚函数的作用(20160805)
- C++之路进阶codevs1269(匈牙利游戏)
- 八大排序算法Java、Python、C++实现 -- 快速排序
- 自己写的C++日志类log
- c++中printf("%5d%5d%5d%5d%5d", ++i, --i, i++, --i, -i--)的问题
- C++ Primer 第7章 知识点回顾
- 八大排序算法 Java、Python、C++实现 -- 冒泡排序
- C语言小游戏之猜数字,三子棋游戏
- Cpp环境【Code[VS]5226】物品选取
- 对typedef关键字的理解
- 复赛模拟试题 - 盛夏的果实 SPFA(队列优化)+二分答案法 重庆一中高2018级竞赛班第七次测试 2016.8.4 Problem 4