forked from rost0413/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongest_Common_Prefix.cpp
47 lines (44 loc) · 988 Bytes
/
Longest_Common_Prefix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
Author: Weixian Zhou, [email protected]
Date: Jul 2, 2012
Problem: Longest Common Prefix
Difficulty: easy
Source: http://www.leetcode.com/onlinejudge
Notes:
Write a function to find the longest common prefix string amongst an array of
strings.
Solution:
Simple.
*/
#include <vector>
#include <set>
#include <climits>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
using namespace std;
class Solution {
public:
string commonPrefix(string a, string b) {
int len = min(a.length(), b.length());
int i;
for (i = 0; i < len; i++) {
if (a[i] != b[i])
break;
}
return a.substr(0, i);
}
string binary(int s, int t, vector<string>& strs) {
if (s > t)
return "";
if (s == t)
return strs[s];
return commonPrefix(binary(s, (s + t) / 2, strs),
binary((s + t) / 2 + 1, t, strs));
}
string longestCommonPrefix(vector<string> &strs) {
return binary(0, strs.size() - 1, strs);
}
};