首页 > 代码库 > Leetcode: ZigZag Conversion
Leetcode: 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)
P A H NA P L S I I GY I R
And 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"
.
分析:本题的难点在于找出字符串s中字符分布在zigzag字符串每行的规律。不难看出,s中位置满足j*(2*nRows-2)的字符被分到第一行,位置满足nRows-1+j*(2*nRows-2)的字符被分配到第nRows行。对于除第一行和第nRows行的其他行,s中位置为i+j*(2*nRows-2)和i+j*(2*nRows-2)+(nRows-1-i)的字符先后被分到第i+1行,此处i = {1,2...,nRows-2}。由上述规律,我们可以轻松写出如下代码:
class Solution {public: string convert(string s, int nRows) { if(nRows == 1) return s; int n = s.length(); if(nRows >= s.length()) return s; string result; for(int i = 0; i < nRows; i++){ if(i == 0 || i == nRows-1){ for(int j = i; j < n; j += 2*nRows-2) result.push_back(s[j]); }else{ for(int j = i; j < n; j += 2*nRows-2 ){ result.push_back(s[j]); if(j+2*(nRows-1-i) < n) result.push_back(s[j+2*(nRows-1-i)]); } } } return result; }};
Leetcode: ZigZag Conversion
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。