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 <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()可用于字符串数组拼接成新的字符串。

其它

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容