【codewars-11】对多行文本做对称变换 Moves in squared strings (I)

This kata is the first of a sequence of four about “Squared Strings”.

You are given a string of n lines, each substring being n characters long: For example:

s = "abcd\nefgh\nijkl\nmnop"

We will study some transformations of this square of strings.

Vertical mirror: vert_mirror (or vertMirror or vert-mirror)
vert_mirror(s) => "dcba\nhgfe\nlkji\nponm"
Horizontal mirror: hor_mirror (or horMirror or hor-mirror)
 hor_mirror(s) => "mnop\nijkl\nefgh\nabcd"
or printed:

vertical mirror   |horizontal mirror   
abcd --> dcba     |abcd --> mnop 
efgh     hgfe     |efgh     ijkl 
ijkl     lkji     |ijkl     efgh 
mnop     ponm     |mnop     abcd 

Task:
Write these two functions
and

high-order function oper(fct, s) where

fct is the function of one variable f to apply to the string s (fct will be one of vertMirror, horMirror)

Examples:
s = "abcd\nefgh\nijkl\nmnop"
oper(vert_mirror, s) => "dcba\nhgfe\nlkji\nponm"
oper(hor_mirror, s) => "mnop\nijkl\nefgh\nabcd"

Note:
The form of the parameter fct in oper changes according to the language. You can see each form according to the language in “Sample Tests”.

Bash Note:
The input strings are separated by , instead of \n. The output strings should be separated by \r instead of \n. See “Sample Tests”.

要点

  • 利用stringstream >> 时以空白为分割符切割字符串.
  • 用反向迭代器来反转字符串.
  • 用压栈和出栈来实现水平镜像.
#include <sstream>
#include <string>
#include <iostream>
#include <cmath>
#include <stack>

class Opstrings
{
public:
    static std::string vertMirror(const std::string &strng){
      std::stringstream ss{strng};
      std::string tmp{};
      std::string res{""};
      
      while(ss>> tmp) {
         if(res!= "") res.append("\n");
        res.append(std::string(tmp.rbegin() , tmp.rend()));
       
      }
      
      return res;
    }
static std::string horMirror(const std::string &strng){
      std::stack<std::string> lines{};
      std::stringstream ss{strng};
      std::string tmp{};
      std::string res{""};
      
      while(ss >> tmp) {
        if(!lines.empty()) lines.push("\n");
        lines.push(tmp);
      }
      while(!lines.empty()){
        res.append(lines.top()) ;
        lines.pop();
      }
      return res;
  
}

    // your high order function oper
    //... oper(...);
  static std::string oper(std::string (*func)(const std::string& ), const std::string &s){
    return  func(s);
  }

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值