leetcode之Longest Common Prefix
来源:互联网 发布:黑客刷枪软件 编辑:程序博客网 时间:2024/06/15 05:40
原题如下:
Write a function to find the longest common prefix string amongst an array of strings.
这道题主要考察对字符串的处理,采用的思路是以第一个字符串为基准,依次与后边的字符串相比较,比较的长度从1逐渐增大,当出现比较不相等的情况时,结束比较。
class Solution {public: string longestCommonPrefix(vector<string> &strs) {string s;if(strs.empty())return s;if(strs.size() == 1)return strs[0];int i = 1;for(i = 1; i <= strs[0].length(); i++){string substr = strs[0].substr(0,i);for(int j = 1; j < strs.size(); j++){if(substr.compare(strs[j].substr(0,i)) != 0)return substr.substr(0,substr.size() - 1);}}return strs[0]; }};这里边有一个要注意的地方是:在截取字符串的子串时,当截取的子串长度超过父串的长度时,返回的就是父串,所以在选择基准串时不必选择最短的一个子串,以任意一个字符串为基准都是可以的,因为当前缀超过最短字串的长度时比较肯定不相等。
0 0
- leetCode 之 Longest Common Prefix
- leetcode之Longest Common Prefix
- leetcode 之 Longest Common Prefix
- leetCode 之 Longest Common Prefix
- LeetCode之Longest Common Prefix
- 【Leetcode】之Longest Common Prefix
- leetcode之 Longest Common Prefix
- LeetCode之Longest Common Prefix
- leetcode 之 Longest Common Prefix
- LeetCode: Longest Common Prefix
- LeetCode Longest Common Prefix
- LeetCode : Longest Common Prefix
- [Leetcode] Longest Common Prefix
- [LeetCode] Longest Common Prefix
- [LeetCode]Longest Common Prefix
- LeetCode-Longest Common Prefix
- [LeetCode] Longest Common Prefix
- LeetCode - Longest Common Prefix
- PHP中获取日期的几种方法
- linux中ctrl+z和ctrl+c的区别
- 测试博文
- putty最佳的的颜色配置
- CodeForces 4B Before an Exam(数学+模拟)
- leetcode之Longest Common Prefix
- shell中类似for循环的还有一个就是select
- python实现二叉树
- 如何获取用户手机当前是否启动了android机的模拟位置功能
- Linux命令学习手册-rsync命令
- 试论计算机病毒及防护
- microsoft word has stopped working解决方法
- 如何安全修改cocoapods上的第三方代码
- vs2010快捷键大全