6. ZigZag Conversion――LeetCode OJ

匿名 (未验证) 提交于 2019-12-03 00:22:01

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

给定一个字符串,以Z形式(我觉得更像倒N)排列,再以正常行列输出。

思路:可以看出一竖条加一斜条形成一个循环。利用该规律将字母保存到对应行的string中,将这些string存入数组中,再按行依次输出。

class Solution { public:     string convert(string s, int numRows) {         vector<string> vecTemp;            if (1 == numRows)            {             return s;           }          //先使整个数组为空         for (int i = 0; i < numRows; ++i) {             vecTemp.push_back("");         }           int iSingleNum = 2*(numRows - 1);//每次循环的个数         for (int i = 0; i < s.length(); ++i)          {             int iRow = i % iSingleNum;//竖着的             if (iRow > numRows - 1)              {                 iRow = iSingleNum - iRow;//斜着的             }             vecTemp[iRow] += s[i];//为该行增加一个值         }          string ret;         for (int i = 0; i < numRows; ++i)          {             ret += vecTemp[i];         }          return ret;     } };

Runtime: 41 ms

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!