Skip to content

Commit 495f34e

Browse files
author
kwu130
committed
feat(src): add 14-longestCommonPrefix
1 parent 4e711d2 commit 495f34e

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

‎src/14-longestCommonPrefix.cpp‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
//
2+
// Created by 1412 on 2025/10/10.
3+
//
4+
5+
#include <bits/stdc++.h>
6+
7+
using namespace std;
8+
9+
class Solution {
10+
public:
11+
string longestCommonPrefix(vector<string>& strs) {
12+
for (int i = 0; i < strs[0].size(); i++) {
13+
for (const auto& str : strs) {
14+
if (i >= str.size() || str[i] != strs[0][i]) {
15+
return strs[0].substr(0, i);
16+
}
17+
}
18+
}
19+
return strs[0];
20+
}
21+
};
22+
23+
void test() {
24+
Solution s;
25+
vector<string> strs = {"flower", "flow", "flight"};
26+
assert(s.longestCommonPrefix(strs) == "fl");
27+
strs = {"dog", "racecar", "car"};
28+
assert(s.longestCommonPrefix(strs) == "");
29+
}
30+
31+
int main() {
32+
test();
33+
return 0;
34+
}

0 commit comments

Comments
 (0)