[LeetCode] Longest Common Prefix
2015-07-12 13:57
375 查看
Use the strs[0] as the reference string and then compare it with the remaining strings from left to right. Once we find a string with length less than strs[0] or different letters in the corresponding position, we cannot move on and should return the longest common prefix string lcp. Each time we finish checking a position and have not returned, we add the letter at that position to lcp.
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if (strs.empty()) return ""; string lcp = ""; int m = strs.size(), n = strs[0].length(); for (int i = 0; i < n; i++) { for (int j = 1; j < m; j++) if (strs[j].length() == i || strs[j][i] != strs[0][i]) return lcp; lcp += strs[0][i]; } return lcp; } };
相关文章推荐
- 百度云服务器 CentOS 图形界面支持
- Java的List和Map作为入参与clone
- 易语言如何写一个取随机数的程序
- 二叉树
- 迭代是人,递归是神(迭代与递归的总结:比较)
- android view 中各函数的执行顺数
- Kademlia算法
- Remove Linked List Elements -- leetcode
- bzoj-2243 染色
- 黑马程序员——Java基础语法
- 关联式容器
- 数据挖掘十大经典算法个人总结
- ie6/7新闻列表错位
- MAC 下查看某个端口被哪个进程占用及杀进程方法
- 解决IE6浏览器下position:fixed固定定位问题
- CCNA综合实验,vlan,vlan间路由,vtp,HSRP,PVST,DHCP。
- Form表单自动提交
- yii2basic下使用ueditor
- 解决只能打开网页不能打开QQ或视频软件问题
- ZOJ 3866 Cylinder Candy(对体积和表面积 积分)