LeetCode—6.ZigZag Conversion

Type: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 = 3Output:"PAHNAPLSIIGYIR"

Example 2:

Input:s = "PAYPALISHIRING", numRows = 4Output:"PINALSIGYAHRPI"Explanation:P    I    NA  L S  I GY A  H RP    I


本题题意为输入一个数字和字符串,将字符串按照zigzag方式写成numRows行的新字符串,并按照从上至下从左到右的顺序输出该新字符串。

本题使用暴力做法,记录每个字符出现的位置,直接输出。

因此寻找位置表达方式:

P         A        H         N

A    P   L  S    I     I    G

         I         R

如图所示,设行数为n,可以将标记的2n-2个字符视为一次循环,size = 2n - 2。

设遍历时行数为i,则在输出第i行时,首先令j = i,输出s[j],接下来判断i是否为第0行或最后一行,若是的话直接输出s[j+size],将j+size赋为新的j值以此类推;若不是第0行或最后一行,则要首先输出s[j+size-2i],接下来再输出s[j+size]即可,然后同上,再次循环。将按顺序读取的所有的字符存在新的字符串中,并输出这个新的字符串。

本题难点在于在此环境中,c++语言无法直接push_back。因此直接开string ret,不能开大小,ret可以用ret += s[j]来赋值。


附代码:

class Solution {

public:

    string convert(string s, int numRows) {

        int n = s.length();

        if(numRows == 1) return s;

        int size = 2 * numRows - 2;

        string ret;

        for(int i=0; i<numRows; i++){

            for(int j=i; j<n; j+=size){

                ret += s[j];

                if(i != 0 && i != numRows-1){

                    int temp = j + size - 2 * i;

                    if(temp < n) ret += s[temp];

                }

            }

        }

        return ret;

    }

};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。