原题
https://www.codewars.com/kata/consecutive-strings/train/cpp
题目
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 “”.
分析
该题是找出连续k个string得出的最长字符串
所以可以直接遍历找出,只要将特殊情况分开处理即可。
代码
#include <string>
#include <vector>
class LongestConsec
{
public:
static std::string longestConsec(std::vector<std::string> &strarr, int k);
};
std::string LongestConsec::longestConsec(std::vector<std::string> &strarr, int k){
std::string res;
size_t n = strarr.size();
for(auto s:strarr){std::cout << s<<std::endl;}
if(n == 0||k > n||k <= 0) return res;
for(size_t i = 0; i < n;i++){
std::string temp;
for(size_t j = i; j < k+i&&j < n;j++){
temp+=strarr[j];
}
if(res.size() < temp.size()){
res = temp;
}
}
std::cout <<"test: ["<<res<<"]"<<std::endl;
return res;
}
参考代码
#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;
};
};
//主要做两个操作:
//把字符串中每k个连续字符串拼接。
//找出最长的拼接字符串
//accumulate()可用于字符串数组拼接成新的字符串。
//作者:jdzhangxin
//链接:http://www.jianshu.com/p/38ef5f413631
//來源:简书
//著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。