Longest Common Prefix
2013-10-10 20:29
239 查看
Write a function to find the longest common prefix string amongst an array of strings.
思路:
先求前两个字符串的公共前缀,然后拿这个前缀和其他字符串进行比对。
另外一种方法是,依次增加result的长度,判断所有的string在这个位是不是相等。虽然复杂度不变,但是代码变得简练很多。
思路:
先求前两个字符串的公共前缀,然后拿这个前缀和其他字符串进行比对。
int min(int a, int b){ if(a < b) return a; return b; } string longestCommonPrefix(vector<string> &strs) { // Note: The Solution object is instantiated only once and is reused by each test case. int n = strs.size(); if(n == 0) return ""; if(n == 1) return strs[0]; string s1 = strs[0], s2 = strs[1]; int i = 0, j; string result = ""; while(s1[i] == s2[i] && i < min(s1.length(), s2.length())){ result += s1[i]; i++; } for(j = 2; j < n; j++){ s1 = strs[j]; i = min(s1.length(), i); while(s1[i-1] != result[i-1] && i>0){ i--; } } result = result.substr(0,i); return result; }
另外一种方法是,依次增加result的长度,判断所有的string在这个位是不是相等。虽然复杂度不变,但是代码变得简练很多。
string longestCommonPrefix(vector<string> &strs) { int n = strs.size(); if(n == 0) return ""; if(n == 1) return strs[0]; int i, j; string result = ""; for(i = 0;;i++){ for(j = 1; j < n; j++){ if(strs[j].length() < i+1 || strs[j][i] != strs[0][i]) break; } if(j < n) break; result += strs[0][i]; } return result; }
相关文章推荐
- 洗盘
- MySQL MyISAM和InnoDB对比
- LU分解求线性方程组的解
- Windows XP Mode
- 线程同步
- Clonezilla 再生龍
- 弹出框JBox实例
- ios开发 MPMoviePlayerController 视频播放器
- 从头到尾彻底解析哈希表算法【转】
- 链表带头节点与不带头节点的区别
- Cocos2d-x 重写draw方法绘制直线等图形时被遮挡覆盖问题的一种解决方案
- Eclipse(PHP、JAVA)的快捷键大全
- boost总结之variant
- python之列表使用方法总结
- 挑战庞果英雄会之子序列的个数
- 1014(2)string的用法
- 结构体定义里的冒号
- cstring转char*
- (贪心5.2.3)POJ 1065 Wooden Sticks(利用数据有序化来进行贪心选择)
- JavaScript 数组详解