ZigZag字符长转换
来源:互联网 发布:吴昕淘宝店omg关了吗 编辑:程序博客网 时间:2024/05/16 16:15
这是leetcode上的一个题目,挺好玩的,在此写下做以记录,其中参考了网友http://blog.csdn.net/zhouworld16/article/details/14121477的笔记,在此表示感谢。
题目如下:
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"
.有上述两个示例可以总结出如下规律:
A) 对于第0行和第怒nRows-1行,两个字符之间相差的 pos = 2*nRows - 2;
B) 对于其他的第i行(i> 0 && i < nRows-1),以第一列为第0列,那么又可以将每行的字符所在列标记为奇数列和偶数列
i) 如果后面一个字符位于奇数列,那么两字符之间相差 pos = 2*(numRows - i) - 2;
ii) 如果后面一个字符位于偶数列,那么两字符之间相差 pos = 2*(i+1)-2;
需要注意的特殊情况:
1) 输入字符串长度s.size <= nRows,那么直接返回该s即可;
2) 注意nRows = 1的情况,因为这个时候其实输出的结果和输入一致,所以直接返回s即可;
3) 在获取字符的时候,要注意不能越界。
实现代码如下:
string convert(string s, int numRows) {if (numRows<= 0)return s;if (s.size() <= numRows || s.size() == 0 || numRows <= 1)return s;int i,j = 0,pos;int len = s.size();string tmp;for (i = 0; i < numRows; i++ ){if (i == 0 || i == numRows - 1){pos = 2*numRows - 2;j = i;while ( j < len){tmp += s[j];j += pos;}}else{int k = 0;j = i;while(j < len){if ( k%2 == 0 ) pos = 2*(numRows - i) - 2;elsepos = 2*(i+1)-2; tmp += s[j];j += pos;k++;}}}return tmp;}
- ZigZag字符长转换
- ZigZag转换 算法
- ZigZag Conversion 锯齿形转换字符串
- [C++]ZigZag Conversion 之字形转换
- 第6题 ZigZag转换
- 短字符和长字符
- 长字符的输出
- 显示长字符
- 字符、字节、字长
- 简单LinuxC程序关于加密(将任意长字符转换为定长整数)
- 简单LinuxC程序关于加密(将任意长字符转换为定长整数)
- [Leetcode #6]ZigZag Conversion 将字符串转换成ZigZag形式
- 6. ZigZag Conversion 之字形字符判断
- NSDate长整型转换
- LeetCode | ZigZag Conversion(锯齿形转换)
- leetcode:ZigZag Conversion锯行转换
- ZigZag Conversion [Z 型字母转换]
- leetcode 6. ZigZag Conversion-Zizag转换
- Qt信号与槽
- STM32中assert_param的使用
- [leetcode 220]Contains Duplicate III
- crontab 定时完成某任务
- web 前端学习笔记(1)
- ZigZag字符长转换
- Attempting to badge the application icon but haven't received permiss...
- 在VS2010中的MFC中配置GDI+
- makefile中的注释
- POJ1556The Doors【判断线段相交+dijkstra】
- UVa 524:Prime Ring Problem(回溯)
- 【转】第一章 Shiro简介
- "Python"学习笔记(三)(数据类型)
- cinのpeek putback