LeetCode6. ZigZag Conversion (C++)

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)排列,然后按行进行输出

解题思路:感觉像是大学期末考喜欢出的那种输出三角形,找出各行之间的关系就OK

class Solution {
public:
    string convert(string s, int numRows) {
        string result="";
        int k=2*numRows-2;
        if(k==0)
            return s;
        for(int i=0;i<numRows;i++){
            if(i==0||i==numRows-1){
                for(int j=i;j<s.length();j=j+k)
                    result+=s[j];
            }
            else{
                for(int j=i;j<s.length();j=j+k){
                    result+=s[j];
                    if((j+k-2*i)<s.length())
                        result+=s[j+k-2*i];
                }
            }
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_41562704/article/details/85368731