您的位置:首页 > 编程语言 > C语言/C++

C++之字符串的zipzag排列(9)---《那些奇怪的算法》

2017-10-14 21:24 393 查看

参考:《one-day-one-leetcode》

针对字符串我们进行zipzag排列,首先我们需要了解什么是zipzag排列,如下图所示:



现在,我们针对这种特性进行代码编写:

#include <iostream>
#include <string>

using namespace std;
string zipzagcode(string s,int row){
int len = s.length();
string result;
int gap = 2 * row - 2;
int row_end = 2;
if (row == 1) return s;
for (int i = 0; i < row; i++){
if (i == 0 || i == row - 1){
int count = 0;
while (i + count*gap < len){
result += s[i + count*gap];
count++;
}
}
else{
int count = 0;
while (count==0||i + count*gap - row_end < len){
if (count == 0){
result += s[i];
}
else{
result += s[i + count*gap - row_end];
if (i + count*gap < len){
result += s[i + count*gap];
}
}
count++;
}
row_end+=2;
}
}
return result;
}
int main(){
string s = "abcdefghijklmn";
string s1 = zipzagcode(s,5);
cout << s1 << endl;
return 0;
}


运行结果:



现在,当然作者提供了另一种解决办法,思路也比较清晰,建议大家也可以进行学习:

#include <iostream>
#include <string>

using namespace std;
//注意底下我们将对j的增长分为两部分:
//1)一部分是当j处于竖列的时候,j只需要增长为gap-2*(j%gap);
//2)当j处于两个竖列之间的时候则需要增长为2*gap-2*(j%gap)。
string zipzagcode_std(string s, int num){
string result;
int gap = 2 * num - 2;
if (num == 1) return s;
for (int i = 0; i < num; i++){
int j = i;
bool flag = true;
if (i == 0 || i == num - 1){
int j = i;
while (j < s.length()){
result += s[j];
j += gap;
}
}
else{
int j = i;
while (j < s.length()){
result += s[j];
j += (j%gap) < num ? (gap - 2 * (j%gap)) : (2 * gap - 2 * (j%gap));
}
}
}
return result;
}
int main(){
string s = "abcdefghijklmn";
string s1 = zipzagcode_std(s,5);
cout << s1 << endl;
return 0;
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐