[C++]LeetCode: 21 Longest Common Prefix
2014-11-18 15:29
281 查看
题目:Write a function to find the longest common prefix string amongst an array of strings.
寻找一组string里的共有的最长前缀;
思路:以vector[0]存储的string为基准,每次同时移动迭代器,当出现不相等结束,返回此时的子字符串。
Attention:需要考虑没有一个匹配的情况,返回的条件运算符;对于循环结束的判断,不需要循环第一个字符串所有的字符。判断结束即可; !!注意变量pos的递增过程中,需要在判断条件中加限制,保证指针不越界。
算法复杂度:O(MN)
Error Code: (my_ori_code)
AC Code:
寻找一组string里的共有的最长前缀;
思路:以vector[0]存储的string为基准,每次同时移动迭代器,当出现不相等结束,返回此时的子字符串。
Attention:需要考虑没有一个匹配的情况,返回的条件运算符;对于循环结束的判断,不需要循环第一个字符串所有的字符。判断结束即可; !!注意变量pos的递增过程中,需要在判断条件中加限制,保证指针不越界。
算法复杂度:O(MN)
Error Code: (my_ori_code)
class Solution { public: string longestCommonPrefix(vector<string> &strs) { //寻找一组string里的共有的最长前缀 //思路:以vector[0]存储的string为基准,每次同时移动迭代器,当出现不相等结束,返回此时的子字符串。 if(strs.size() == 0) return NULL; string ret = strs[0]; bool tag = 0; for(int j = 0; j < strs[0].length(); j++) //不需要这么做 { for(int i = 0; i < strs.size(); i++) { if(strs[i][j] != strs[0][j]) { tag = 1; break; } //如果中间有不匹配的,返回j之前的字符串,字符个数为j个。 if(tag == 1) return ret.substr(0, j); } } return ret; } };
AC Code:
class Solution { public: string longestCommonPrefix(vector<string> &strs) { //寻找一组string里的共有的最长前缀 //思路:以vector[0]存储的string为基准,每次同时移动迭代器,当出现不相等结束,返回此时的子字符串。 //Attention:需要考虑没有一个匹配的情况,返回的条件运算符; if(strs.size() == 0) return ""; bool done = false; //pos置-1有好处。 int pos = -1; while(!done) { //超出strs的第一个字符串的长度,结束循环。不需要循环第一个字符串所有的字符。判断结束即可。 if(++pos == strs[0].size()) break; //这样写含义更加清晰。保证代码的可读性好。 char samec = strs[0][pos]; for(int i = 1; i < strs.size(); i++) { //加句strs[i].size()<=pos更加安全,保证不越界 if(strs[i].size() <= pos || strs[i][pos] != samec) { done = true; break; } } } //pos在首次循环时已经变成0 return pos != 0 ? strs[0].substr(0, pos) : "" ; } };
相关文章推荐
- LeetCode刷题(C++)——Longest Common Prefix(Easy)
- LeetCode 之 Longest Common Prefix — C++实现
- LeetCode上Longest Common Prefix的C++解法
- [C++]LeetCode 14: Longest Common Prefix(最长公共前缀)
- leetcode 14 Longest Common Prefix C++
- 【leetcode c++】14Longest Common Prefix
- [LeetCode] 014. Longest Common Prefix (Easy) (C++/Java/Python)
- leetcode_c++:Longest Common Prefix(014)
- LeetCode 14 — Longest Common Prefix(C++ Java Python)
- 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