Leetcode.Longest Common Prefix
2015-06-24 11:33
330 查看
Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.找最长公共前缀
class Solution { public: string longestCommonPrefix(vector<string> &strs) { if(strs.size() == 0) return string(""); int strIdx = 0; //choose the smallest string first for(int i = 1; i < strs.size(); ++i) if(strs[i].size() < strs[strIdx].size()) strIdx = i; int commonLen = strs[strIdx].size(); for(int i = 0; i < strs.size(); ++i) { if(i == strIdx) continue; int curLen = 0; for(int j = 0; j < strs[i].size() && j < commonLen; ++j) { if(strs[strIdx][j] == strs[i][j]) curLen++; else break; } commonLen = curLen; } return strs[strIdx].substr(0, commonLen); } };
相关文章推荐
- 内存管理机制 Thread 1:EXC_BAD_ACCESS(code=EXC_I386_GPFLT)错误
- WPF中的窗体Show()和ShowDialog()区别
- MongoDB 进程控制系列二:结束进程
- php浮点型以及精度问题
- android布局属性
- 抽象工厂模式
- ecshop查询搜索记录最多的前10条
- linux shell 导出mongodb 数据库 & 导出 mysql数据库
- MYSQL远程连接解决办法
- 连接时出现:Can't open display: localhost:10.0
- MySQL学习系列2:数据类型宽度/查看字段长度
- TCP/IP和socket
- openstack中Nova组件images的所有python API 汇总
- dedecms列表页文章有图调用缩略图 无图留空或自定义图片的方法!
- 使用MDT2013部署Win8系统之二-创建MDT目录共享
- 同步,异步,阻塞,非阻塞 -IO
- 二叉树、平衡二叉树、完全二叉树、满二叉树
- diamond专题(一)-- 简介和快速使用
- 在gcc中定义符号常量
- 二叉树、平衡二叉树、完全二叉树、满二叉树