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
|
// Instructions for the exercise:
// You are given an array strarr of strings and an integer k. Your task is to
// return the first longest string consisting of k consecutive strings taken
// in the array.
// #Example: longest_consec(["zone", "abigail", "theta", "form", "libe",
// "zas", "theta", "abigail"], 2) --> "abigailtheta"
// n being the length of the string array, if n = 0 or k > n or k <= 0 return "".
#include <iostream>
#include <limits>
#include <string>
#include <vector>
std::string longestConsec(const std::vector<std::string>& strarr, int k);
void waitForEnter();
int main()
{
std::vector<std::string> vecstr { "zone", "abigail", "theta", "form",
"libe", "zas", "theta", "abigail" };
int consec = 2;
std::cout << "longest sequence: " << longestConsec(vecstr, consec) << '\n';
waitForEnter();
return 0;
}
std::string longestConsec(const std::vector<std::string>& strarr, int k)
{
if(strarr.empty() || k > strarr.size() || k<= 0) { return ""; }
int longest {}, position {};
for(int i {}; i<strarr.size()-k; ++i) {
int total {};
for(int j{i}; j<k+i; ++j) { total += strarr.at(j).length(); }
if(longest < total) {
longest = total;
position = i;
}
}
std::string melt;
for(int i{position}; i<k+position; ++i) { melt += strarr.at(i); }
return melt;
}
void waitForEnter()
{
std::cout << "\nPress ENTER to continue...\n";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
|