[leetcode] zigzag transformation

z-sorts a given string from top to bottom, left to right, based on the number of rows given. For example, if the input string is “LEETCODEISHIRING” and the number of lines is 3, list it like this:

L C I R
E T O E S I I G
E D H N

After

, your output needs to be read line by line from left to right to produce a new string, such as “LCIRETOESIIGEDHN”.
:
string convert(string s, int numRows);

  • example 1:
    input: s = “LEETCODEISHIRING”, numRows = 3
    output: “LCIRETOESIIGEDHN”

  • example 2:
    input: s = “LEETCODEISHIRING”, numRows = 4
    0 output: “LDREOEIIECIHNTSG”
    interpretation :
    LDR
    EOEII
    ECIHN
    TSG

Source:

button force (LeetCode)
link: https://leetcode-cn.com/problems/zigzag-conversion


train of thought (have a reference problem solution)

  • the first idea is to establish a two-dimensional array, violence will character in order fill in the
  • set a says going in the direction of variables, when the z glyph to the first line/change direction when the last line
  • dir represents a string array of rows, according to which line going to judge the next character is inserted into the
  • finally connect string array all, become a string

    code

    class Solution {
    public:
        string convert(string s, int numRows) {
            if(numRows==1)
            {
                return s;
            }
            int n=s.length();
            vector<string> rows(min(n,numRows));
            
            int dir=0;
            bool going=false;
            for(char c : s)
            {
                rows[dir]+=c;
                if(dir==0 || dir==numRows-1) going=!going;
                dir+=going?1:-1;
            }
    
            string a;
            for(string x:rows) 
            {
                a+=x;
            }
            return a;
        }
    };
    

    summary

    • get a new method of traversing strings, but also understand the string connection

Read More: