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 “”.
分析

该题是找出连续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
//來源:简书
//著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值