Longest Common Prefix
来源:互联网 发布:出国留学 知乎 编辑:程序博客网 时间:2024/05/20 17:41
Write a function to find the longest common prefix string amongst an array of strings.
实现:
class Solution {public: string longestCommonPrefix(vector<string>& strs) { string res = ""; int cnt = 0; if(strs.size() == 0 ) return res; if(strs.size() == 1) return strs[0]; while(true){ if(cnt >= strs[0].size()){ return res; } char ch = strs[0][cnt] ; bool flag = false; for(int i = 1 ; i < strs.size(); ++i){ if(cnt>=strs[i].size() || strs[i][cnt]!=ch){ flag = true; break; } } if(flag||strs.size()<=1) break; res+=ch; ++cnt; } return res; }};
自己的实现过于复杂,有简单的实现方式:
class Solution {public: string longestCommonPrefix(vector<string>& strs) { string res = ""; for(int i = 0;strs.size() > 0;res+=strs[0][i],++i){ for(int j = 0 ; j < strs.size() ; ++j){ if(i >= strs[j].size() || (j > 0 && strs[j-1][i] != strs[j][i])) return res; } } return res; }};
0 0
- LeetCode: Longest Common Prefix
- LeetCode Longest Common Prefix
- LeetCode : Longest Common Prefix
- [Leetcode] Longest Common Prefix
- leetcode6:Longest Common Prefix
- leetcode22: longest common prefix
- [LeetCode] Longest Common Prefix
- Leetcode14: Longest Common Prefix
- Longest Common Prefix
- Longest Common Prefix
- Longest Common Prefix
- [LeetCode]Longest Common Prefix
- Longest Common Prefix
- LeetCode-Longest Common Prefix
- Longest Common Prefix
- [LeetCode] Longest Common Prefix
- Longest Common Prefix
- LeetCode - Longest Common Prefix
- Abstract Factory(抽象工厂模式)
- android Sqlite expert中使用SQL 语句插入两条记录
- 在Linux下如何运行.sh文件
- [精]Oracle数据库日常维护命令
- bzoj 4353: Play with tree (树链剖分)
- Longest Common Prefix
- 在CentOS上搭建PHP服务器环境
- Mysql自动备份脚本
- Hibernate安装Hibernate tools
- Python语言学习:Beautiful Soup四个对象的具体用法
- Android程序登录界面设计
- InputStreamReader 和FileReader的区别及InputStream和Reader的区别
- .closest(selector)和.parents()
- web项目shiro与spring集成 maven依赖及web配置详解