-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestCommonPrefix.hpp
50 lines (35 loc) · 1.05 KB
/
LongestCommonPrefix.hpp
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
48
49
50
//
// LongestCommonPrefix.hpp
// LeetCode
//
// Created by Salvatore on 18/4/24.
//
#ifndef LongestCommonPrefix_hpp
#define LongestCommonPrefix_hpp
#include <stdio.h>
namespace LongestCommonPrefix {
string longestCommonPrefix(vector<string>& strs) {
sort(strs.begin(), strs.end());
string &front = strs.front();
string &back = strs.back();
int maxSize = min(front.size(), back.size());
string ans = "";
for(int i = 0; i < maxSize; ++i){
if(front[i] != back[i]) break;
ans += front[i];
}
return ans;
}
void test() {
vector<vector<string>> cases = {
{"flower","flow","flight"},
{"dog","racecar","car"}
};
vector<string> expected = {"fl", ""};
for(int i = 0; i < cases.size(); ++i){
string result = longestCommonPrefix(cases[i]);
assert(result == expected[i], result, expected[i]);
}
}
}
#endif /* LongestCommonPrefix_hpp */