首页 > 技术文章 > LeetCode 6. Z字形变换(ZigZag Conversion)

wmx24 2018-08-28 11:47 原文

题目描述

 

将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:

P   A   H   N
A P L S I I G
Y   I   R

之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"

实现一个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);

示例 1:

输入: s = "PAYPALISHIRING", numRows = 3
输出: "PAHNAPLSIIGYIR"

示例 2:

输入: s = "PAYPALISHIRING", numRows = 4
输出: "PINALSIGYAHRPI"
解释:

P     I    N
A   L S  I G
Y A   H R
P     I

 

解题思路

 

把字符串按行输出时要考虑首尾与中间情况,所以首先计算出每个Z字形周期内的字符个数,然后求出周期数,接着对每一行的每个周期依次遍历,对于首尾行的字符直接添加;对于中间行的字符要再添加Z字中间的字符。对于最后一个周期,要判断是否走到了字符串末尾。

 

代码

 

 1 class Solution {
 2 public:
 3     string convert(string s, int numRows) {
 4         if(numRows == 1) return s;
 5         int cycle = 2 * numRows - 2;
 6         int numZ = s.length() / cycle;
 7         string res = "";
 8         for(int i = 0; i < numRows; i++){
 9             for(int j = 0; j <= numZ; j++){
10                 if(j * cycle + i >= s.length()) continue;
11                 if(i == 0 || i == numRows - 1)
12                     res += s[j * cycle + i];
13                 else{
14                     res += s[j * cycle + i];
15                     int idx = j * cycle + cycle - i;
16                     if(idx < s.length())
17                         res += s[idx];
18                 }
19             }
20         }
21         return res;
22     }
23 };

 

推荐阅读