LeetCode 6 ZigZag Conversion题解
来源:互联网 发布:ubuntu for arm 编辑:程序博客网 时间:2024/05/29 16:29
题目地址:https://leetcode.com/problems/zigzag-conversion/
题目:
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)
字符串"PAYPALISHIRING"写成给定行数的循环对角结构,如下:(你可能想要将这个图形修改的更加易读)
P A H NA P L S I I GY I R
And then read line by line: "PAHNAPLSIIGYIR"
然后一行行读成“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"
.
转化“PAYPALISHIRING,3”应得“PAGNAPLSIIGYIR”
题解:
1)什么是ZigZag(循环对角结构)?
举个5行的ZigZag存储1到n的数字的例子,如下图:
1 9 17...2 810 1618...3 7 11 15 19...46 1214 20...5 13 21...给定行数为rowsNum,行号为0~rowsNum-1。
我们可以看出,整列的数字,同一行的两个数字之间相差2*(rowsNum-1),比如第一行的1,9,17,相差8=2*(行数为5-1)。
整列数字间的数字,与同行下一数字相差2*行号,比如第二行的8和10差2=2*行号为1,第三行的7和11差4=2*行号为2。(这样的数字位置特点:非首行,非末行),)
3)C++代码
class Solution {public: string convert(string s, int numRows) { int l=s.length(); string str=""; if(l==0) return str; if(numRows==1||l<=numRows) return s; else { for(int j=0;j<numRows;j++) { for(int i=j;i<l;i+=(numRows-1)*2) { str+=s.at(i); if(j!=0&&j!=numRows-1&&i+(numRows-1)*2-2*j<l) { str+=s.at(i+(numRows-1)*2-2*j); } } } } return str; }};
4)Java代码
public class Solution { public String convert(String s, int numRows) { int l=s.length(); String str=""; if(l==0) return str; if(numRows==1||l<=numRows) { return s; }else { for(int j=0;j<numRows;j++) { for(int i=j;i<l;i+=2*(numRows-1)) { str+=s.charAt(i); if(j!=0&&j!=numRows-1&&(i+2*(numRows-1)-2*j)<l) { str+=s.charAt(i+2*(numRows-1)-2*j); } } } } return str; }}
- LeetCode 6 ZigZag Conversion题解
- LeetCode题解-6-ZigZag Conversion
- LeetCode 6 ZigZag Conversion 题解
- LeetCode题解:ZigZag Conversion
- LeetCode题解:ZigZag Conversion
- 【LeetCode】ZigZag Conversion 题解
- LeetCode题解——6ZigZag Conversion
- 《LeetBook》leetcode题解(6): ZigZag Conversion[E]
- leetcode题解||ZigZag Conversion问题
- LeetCode题解-6. ZigZag Conversion
- 6. ZigZag Conversion LeetCode题解
- Leetcode题解-6. ZigZag Conversion
- LeetCode 6 - ZigZag Conversion
- LeetCode 6: ZigZag Conversion
- LeetCode(6)ZigZag Conversion
- Leetcode【6】:ZigZag Conversion
- [leetcode 6] ZigZag Conversion
- LeetCode 6 ZigZag Conversion
- YAF label getcookie() php加密函数 自己调用任意模板
- 51nod 1095 Anigram单词
- <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getSe
- caffe平台快速搭建:caffe+window7+vs2013
- AdaBoost
- LeetCode 6 ZigZag Conversion题解
- 如何退出SCALA命令界面
- Redis-JedisPoolConfig配置
- 一次网络调整的过程
- 线程同步和异步
- 手把手教学MFC吃豆子教程
- 队列
- XML文件转义字符的处理
- 能信安_市场运作及产品分析v1.1.0