原题
http://www.codewars.com/kata/56dbe0e313c2f63be4000b25/train/cpp
题目
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"
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)
s = "abcd\nefgh\nijkl\nmnop"
oper(vert_mirror, s) => "dcba\nhgfe\nlkji\nponm"
oper(hor_mirror, s) => "mnop\nijkl\nefgh\nabcd"
分析
- 字符串矩阵镜像非常简单,主要分为三步,分割->交换位置->合并
-
oper()
主要是把函数作为参数。
参考答案
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
string horMirror(const string &str){
// 字符串以回车换行分割成数组
istringstream iss(str);
vector<string> str_vec;
str_vec.assign(istream_iterator<string>(iss),istream_iterator<string>());
// 交换字符串位置
swap_ranges(begin(str_vec),(str_vec.begin()+str_vec.size()/2),str_vec.rbegin());
// 把字符串数组组成字符串
ostringstream oss;
copy(begin(str_vec),end(str_vec),ostream_iterator<string>(oss,"\n"));
string res = oss.str();
res.pop_back(); // 除去最后一个回车。
return res;
}
string vertMirror(const string &str){
// 字符串以回车换行分割成数组
istringstream iss(str);
vector<string> str_vec;
str_vec.assign(istream_iterator<string>(iss),istream_iterator<string>());
// 遍历字符串
for(auto& s:str_vec){
// 交换字符位置
swap_ranges(begin(s),(s.begin()+s.size()/2),s.rbegin());
}
// 把字符串数组组成字符串
ostringstream oss;
copy(begin(str_vec),end(str_vec),ostream_iterator<string>(oss,"\n"));
string res = oss.str();
res.pop_back(); // 除去最后一个回车。
return res;
}
string oper(string (func)(const string &),const string &s){
return func(s);
}
说明
1.字符串分割成向量的C++惯用法(流默认以空格、回车、Tab作为分割符)。
2.容器范围数据交换swap_range()
。
3.容器元素连接成字符串。
其它
无