原题
https://www.codewars.com/kata/consecutive-strings/train/cpp
题目
You are given an array
strarr
of strings and an integerk
. Your task is to return the first longest string consisting ofk
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, ifn = 0
ork > n
ork <= 0
return""
.
求向量由strarr
中k
个连续字符串组成的第一个最长的字符串。
分析
主要做两个操作:
- 把字符串中每
k
个连续字符串拼接。 - 找出最长的拼接字符串
参考答案
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
#include <numeric>
using namespace std;
class LongestConsec
{
public:
static string longestConsec(vector<string> &strarr, int k){
if(strarr.size() == 0 or k <= 0 or k > strarr.size()){
return "";
}
string res;
auto it = strarr.begin();
while(it + k <= strarr.end()){
// 连接字符串
string temp = accumulate(it,it+k,string());
// 获取拼接后最长的字符串
if(res.size() < temp.size()){
res = temp;
}
it++;
}
return res;
};
};
说明
accumulate()
可用于字符串数组拼接成新的字符串。
其它
无