6. ZigZag Conversion
来源:互联网 发布:查看informix端口 编辑:程序博客网 时间:2024/06/11 02:11
打印之字形字符图案带打印程序:转自
https://www.2cto.com/kf/201311/259392.html
The string "PAYPALISHIRING"
is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H NA P L S I I GY I RAnd then read line by line:
"PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)
should return "PAHNAPLSIIGYIR"
. 按照它题目给出来的例子,不熟悉的话,还真不知道他想我们干嘛,所以还是看看图样就清楚了,如下面的运行打印图:
一. 5行时打印结果
二. 8行时打印结果
三. 10行时打印结果
这就清楚了,利用输入字符打印一个倒立之字形的图样。
关键是要会如何计算各个字符的位置,这就需要数学知识了,根据特殊推导出公式来。
主要是3个公式:
1 之字形行数为nRows,那么每次重复样出现前的间隔字符为zigSpan = nRows*2-2;
2 第一行和最尾一行都是存放一个字符的,所以存储的字符为间隔为zigSpan的字符
3 中间行是需要额外存储多一个字符的,存储的字符位置是: zigSpan + j - 2*i(其中i为行数,j为该行第几个字符了)
如下面程序:
class Solution { public: string convert(string s, int nRows) { if(nRows <= 1 || s.length() < 3 || s.length() <= nRows) return s; string s2; int zigSpan = nRows*2 - 2; for (int i = 0; i < nRows; i++) { for (int j = i; j < s.length(); j+=zigSpan) { s2.push_back(s[j]); //注意:推导出zigSpan+j-2i的数学公式,一点都不能错 if (i != 0 && i != nRows-1 && zigSpan+j-2*i<s.length()) { s2.push_back(s[zigSpan+j-2*i]); } } } return s2; } };下面是打印测试程序,运行结果如前面看到的图样:
void printZigzag(const string &s, int nRows) { if(s.empty() || nRows < 1) return; if (nRows == 1) { cout<<s<<endl; return; } int zigSpan = nRows*2 - 2; int zig = nRows - 2; for (int i = 0; i < nRows; i++) { for (int j = i; j < s.length(); j+=zigSpan) { cout<<s[j]; //注意:推导出zigSpan+j-2i的数学公式,一点都不能错 if (i != 0 && i != nRows-1 && zigSpan+j-2*i<s.length()) { for (int r1 = 0; r1 < zig-i; r1++) { cout<<" "; } cout<<s[zigSpan+j-2*i]; for (int r2= 0; r2 < i-1; r2++) { cout<<" "; } } else { for (int r = 0; r < zig; r++) { cout<<" "; } } } cout<<endl; } } int main() { string str1 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; Solution solu; int nRows = 5; //string str2 = solu.convert(str1, nRows); //cout<<str2<<endl; printZigzag(str1, nRows); system("pause"); return 0; }
阅读全文
0 0
- LeetCode 6. ZigZag Conversion
- LeetCode --- 6. ZigZag Conversion
- LeetCode 6.ZigZag Conversion
- [Leetcode] 6. ZigZag Conversion
- 6.ZigZag Conversion
- 6. ZigZag Conversion
- 6. ZigZag Conversion
- 【leetcode】6. ZigZag Conversion
- 6.ZigZag Conversion
- 6. ZigZag Conversion
- 6.ZigZag Conversion
- [LeetCode] 6.ZigZag Conversion
- LeetCode - 6. ZigZag Conversion
- 6. ZigZag Conversion
- 6. ZigZag Conversion
- 6.ZigZag Conversion(93.10%)
- 6. ZigZag Conversion
- [leetcode] 6. ZigZag Conversion
- 主动式冷却解决方案提升高亮度 LED 性能---凯利讯半导体
- stm32f103之GP2Y1014AU
- K链表反转一次和多次
- 第十五周项目2
- freeswitch的配置和拨打电话尝试
- 6. ZigZag Conversion
- json解析错误
- 工具类
- RecyclerView的加载显示多种布局
- Hessian序列化详解
- 关于项目中的http和https的分析和理解
- 自保存业务层返回bean类
- mysql workbenchd导入excel数据步骤
- ZYNQ HLS工具系列(一) HLS图像处理入门