码迷,mamicode.com
首页 > 其他好文 > 详细

19.1.20 [LeetCode 6]ZigZag Conversion

时间:2019-01-20 15:56:32      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:click   you   return   hrp   wan   nap   als   sed   class   

Medium

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   N
A P L S I I G
Y   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 s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I
技术分享图片
 1 class Solution {
 2 public:
 3     string convert(string s, int numRows) {
 4         int group = numRows + numRows - 2;
 5         if (group <=1)return s;
 6         int i, size = s.length();
 7         string ans = "";
 8         for (int i = 0; i < size; i += group)
 9             ans+=s[i];
10         for (int j = 1; j < numRows-1; j++) {
11             for (i = 0; i < size; i += group) {
12                 if(i+j<size)
13                     ans+=s[i+j];
14                 if(i+group-j<size)
15                     ans+=s[i + group - j];
16             }
17         }
18         for (int i = numRows - 1; i < size; i += group)
19             ans+=s[i];
20         return ans;
21     }
22 };
View Code

简单的模拟,坑点在于有类似 numRows=1 的情况

19.1.20 [LeetCode 6]ZigZag Conversion

标签:click   you   return   hrp   wan   nap   als   sed   class   

原文地址:https://www.cnblogs.com/yalphait/p/10295029.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!