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

16 篇文章 0 订阅

参考:《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;
}

运行结果:
这里写图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值