Reverse or rotate? -- 6Kyu

原题

https://www.codewars.com/kata/reverse-or-rotate/train/cpp

题目

The input is a string str of digits. Cut the string into chunks (a chunk here is a substring of the initial string) of size sz (ignore the last chunk if its size is less than sz).
If a chunk represents an integer such as the sum of the cubes of its digits is divisible by 2, reverse that chunk; otherwise rotate it to the left by one position. Put together these modified chunks and return the result as a string.
If
sz is <= 0 or if str is empty return ""
sz is greater (>) than the length of str it is impossible to take a chunk of size sz hence return "".

Examples:

revrot("123456987654", 6) --> "234561876549"
revrot("123456987653", 6) --> "234561356789"
revrot("66443875", 4) --> "44668753"
revrot("66443875", 8) --> "64438756"
revrot("664438769", 8) --> "67834466"
revrot("123456779", 8) --> "23456771"
revrot("", 8) --> ""
revrot("123456779", 0) --> "" 
revrot("563000655734469485", 4) --> "0365065073456944"

分析

本题主要是数字字符串处理。主要分为三个要点。

  1. 数组字符串累计求和
  2. 字符串反转
  3. 字符串旋转

这三个问题都可以使用STL算法函数模板解决。

参考答案

#include <string>
#include <numeric>
using namespace std;

class RevRot
{
public:
    static std::string revRot(const std::string &str, unsigned int sz){
      if(0 == sz or str.empty() or sz > str.size()){
        return "";
      }
      size_t count(str.size()/sz);
      string res(str,0,count*sz);// 保留满足sz部分

      auto it = res.begin();
      while(it < res.end()){
        if(accumulate(it,it+sz,'0',[](char r,char l){return (r-'0')+(l-'0');})%2){
          rotate(it,it+1,it+sz);
        }else{
          reverse(it,it+sz);
        }
        it += sz;
      }
      return res;
    };
};

说明

其它

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

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,414评论 0 23
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • 活着 就好像是在梦中 像一棵蒲公英 随风飘散 风起 风停 飞扬 坠落 好像梦一场 岁月叫我不要再回望 前方的路更宽广
    blue布拉格girls阅读 2,405评论 0 0
  • 今天是个特殊的日子,我想对你说一声我爱你。 2016年5月18日,第一次和你相遇。到现在的2017年5月20日,认...
    思远同学阅读 3,392评论 9 9
  • 年初为自己定了计划,说今年一定要读完50本书籍,到目前已经读了10本左右,然而看过也就忘记了,根本就记不住多少内容...
    Makiyoko阅读 1,267评论 0 0