-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest_common_prefix.cpp
More file actions
28 lines (27 loc) · 914 Bytes
/
Copy pathlongest_common_prefix.cpp
File metadata and controls
28 lines (27 loc) · 914 Bytes
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
/*
LeetCode: Problem 9: Palindrome Number
Difficulty Level: Easy
Name: Nava Nizard
Date: May 10, 2025
Programming Language: C++
Instructions: Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Approach: Sort the vector alphabetically, compare each character in the first and last string of the vector
to find the longest common prefix.
*/
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string prefix; //create an empty string
sort(strs.begin(), strs.end()); //alphabetical order
for (int i = 0; i < strs[0].size(); i++){
if (strs[0][i] == strs[strs.size() - 1][i]){
prefix+= strs[0][i];
}
else {
break; //stop at the first mismatch
}
}
return prefix;
}
};