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; }
运行结果:
相关文章推荐
- C++之最长回文字符串的判断(8)---《那些奇怪的算法》
- C++之实现大顶堆(1)---《那些奇怪的算法》
- C++之数字容器装水问题(10)---《那些奇怪的算法》
- C++之快速排序(3)---《那些奇怪的算法》
- C++搜索与回溯算法之字符串全排列
- C++之树的层序遍历和深度优先遍历(先序遍历)(14)---《那些奇怪的算法》
- C++之实现两个链表合并(迭代和递归版本)(19)---《那些奇怪的算法》
- C++之最长公共子串(最长子数组和)(22)---《那些奇怪的算法》
- C++之整数转化为罗马数字(11)---《那些奇怪的算法》
- C++之求解二叉树中所有从根节点到叶节点的所有路径(23)---《那些奇怪的算法》
- [互联网面试笔试汇总C/C++-11] 字符串全排列和组合算法
- C++之归并排序(7)---《那些奇怪的算法》
- C++之平衡二叉树的判定(25)---《那些奇怪的算法》
- C++之罗马数字转换为整型数字(12)---《那些奇怪的算法》
- C++实现两个有序链表合并(17)---《那些奇怪的算法》
- C++实现二叉树的镜像操作(18)---《那些奇怪的算法》
- C++之求取vector中三个元素和和给定元素最接近的值(15)---《那些奇怪的算法》
- C++之根据组合遍历顺序生成二叉树(25)---《那些奇怪的算法》
- C++之最长公共子序列(21)---《那些奇怪的算法》
- C++之堆的实现(5)---《那些奇怪的算法》