最长公共前缀II

题目: 已知某二叉树的先序序列和中序序列,编程计算并输出该二叉树的后序序列。

输入格式:

1
字符串数组

输出格式:

1
前缀字符串

输入样例:

1
["flower","flow","flight"]

输出样例:

1
"fl"

思路:
用一个变量来保存最长的前缀,将第一个数组字符串作为基串,逐个匹配后面元素的字符串。

代码:

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
#include <bits/stdc++.h> 
using namespace std;

class Solution{
public:
string longestCommonPrefix(vector<string> &strs){
if(strs.empty() || strs.size() == 0) return "";
vector<string>::iterator t;
string prefix;
char stemp;
int i = 0;
while(1) {
stemp = strs[0][i];
for(int j = 0; j < strs.size(); j++) {
if(stemp != strs[j][i])
return prefix;
}
prefix += stemp;
i++;
}
return prefix;
}
};

int main(void) {
vector<string> strs;
// strs.push_back("flower");
// strs.push_back("flow");
// strs.push_back("flight");

// strs.push_back("dog");
// strs.push_back("racecar");
// strs.push_back("car");

strs.push_back("dog");
strs.push_back("dogracecar");
strs.push_back("docar");

Solution s;
cout << s.longestCommonPrefix(strs);

return 0;
}