Consecutive strings -- 6 Kyu

原题

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 "".

求向量由strarrk个连续字符串组成的第一个最长的字符串。

分析

主要做两个操作:

  1. 把字符串中每k个连续字符串拼接。
  2. 找出最长的拼接字符串

参考答案

#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

class LongestConsec
{
public:
    static string longestConsec(vector &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()可用于字符串数组拼接成新的字符串。

其它

你可能感兴趣的:(Consecutive strings -- 6 Kyu)