Longest Common Prefix
2016-05-03 12:08
441 查看
Write a function to find the longest common prefix string amongst an array of strings.
Solution
一开始只想到从左到右横扫一遍,却没想到 divide and conquer
Solution
一开始只想到从左到右横扫一遍,却没想到 divide and conquer
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if(strs.empty()) return ""; string comp = strs[0]; for( int i = 1; i < strs.size(); i++ ){ if(strs[i].size() < comp.size()) comp = strs[i]; } int left = 0, right = comp.size() - 1; while( left <= right ) { int mid = (left + right) / 2; bool flag = false; for (string str : strs) { if(str == comp) continue; if(str.substr(0, mid +1) != comp.substr(0, mid + 1)) { right = mid - 1; flag = true; break; } } if(!flag) left = mid + 1; } return right == -1 ? "" : comp.substr(0, right + 1); } };
相关文章推荐
- divide and conquer in Date Structures and Algorithm Analysis in C
- [leetCode] Different Ways to Add Parentheses
- Leetcode#53||Maximum Subarray
- Leetcode#4||Median of Two Sorted Arrays
- Maximum Subarray
- Majority Element
- Maximum Subarray
- 【Leetcode】Combination Sum III #216
- [leetcode] 287. Find the Duplicate Number
- [leetcode] 95. Unique Binary Search Trees II
- [leetcode] 312. Burst Balloons
- [leetcode] 53. Maximum Subarray
- [leetcode] 241. Different Ways to Add Parentheses
- [leetcode] 23. Merge k Sorted Lists
- Leetcode NO.278 First Bad Version
- 分治 Divide and Conquer 局部最小值 local optimal 棋盘问题
- 算法导论----VLSI芯片测试; n个手机中过半是好的,找出哪些是好手机
- 算法----中位数算法的妙用(更新中)
- [hihoCoder] 压缩字符串 解题报告
- (Java)LeetCode-53. Maximum Subarray