class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
for (int i = 0; i < strs.size(); i++) {
for (int j = 0; j < strs[i].size(); j++) {
if (strs[i][j] == strs[i + 1][j + 1]) {
// return the letters or add them to something and return that idk
}
}
}
}
};``` I'm a beginner in C++ and I'm attempting this question, and I don't event know if the code above is correct. I'm trying to loop through the individual letters of a string in vector and compare them with the next to see if they are the same to find the longest prefix. I'm also not sure how to make it so that it discards it if its not in a row.
any help would be appreciated
#longest common prefix
12 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.
question for refrence^
;compile cpp
#include <iostream>
#include <vector>
#include <string>
std::string longestCommonPrefix(std::vector<std::string>& strs) {
if (strs.empty()) {
return "";
}
// Start with the first string as the prefix candidate
std::string prefix = strs[0];
for (int i = 1; i < strs.size(); ++i) {
int j = 0;
while (j < prefix.length() && j < strs[i].length() && prefix[j] == strs[i][j]) {
++j;
}
prefix = prefix.substr(0, j); // Update the prefix
}
return prefix;
}
int main() {
std::vector<std::string> strings[2] = {{"flower", "flow", "flight"}, {"dog", "racecar", "car"}};
std::string result1 = longestCommonPrefix(strings[0]);
std::cout << "Longest common prefix: " << result1 << std::endl;
std::string result2 =
longestCommonPrefix(strings[1]);
std::cout << "Longest common prefix: " << result2 << std::endl;
return 0;
}```
Program Output
Longest common prefix: fl
Longest common prefix:
µBrain#6100 | 70ms | c++ | x86-64 gcc 13.2 | godbolt.org
woah
@devout oracle how did you make it so that it updates if the common letters appear in a row?
// Update the prefix
