LC6. Z-shaped transformation

Z-shaped transformation

Problem description:
  arrange a given character string in a zigzag pattern from top to bottom and from left to right according to the given number of lines.

For example, when the input string is "LEETCODEISHIRING" and the number of rows is 3, the arrangement is as follows:

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

After that, your output needs to be read line by line from left to right, producing a new string, such as: "LCIRETOESIIGEDHN".

Please implement this function that transforms the string to the specified number of lines:

string convert(string s, int numRows);

Example 1:

Input: s = "LEETCODEISHIRING", numRows = 3
Output: "LCIRETOESIIGEDHN"

Example 2:

Input: s = "LEETCODEISHIRING", numRows = 4
Output: "LDREOEIIECIHNTSG"
Explanation:
L D R
E OE I I
EC I H N
T S G

Problem-solving ideas:

  This question is about finding rules, many of the solutions are to find its period 2n-2, I am relatively simple and rude, directly store the characters of each column in the corresponding container, the longest column must be numRows, one in the middle It is sufficient to store from the back to the front, basically fixed at numRows-2.

code show as below:

#include<iostream>
#include<vector> 
using namespace std;
string convert(string s, int numRows) {
        string a[numRows];
        if(s.size()==numRows){//字符串的大小等于numRows直接返回s
            return s;
        }
        for(int i=0;i<s.size();i++){
            for(int j=0;j<numRows&&i<s.size();j++,i++){//读取完整的一列,i记得要判断会不会出界
                a[j]+=s[i];
            }
            for(int j=numRows-2;j>=1&&i<s.size();j--,i++){//从后往前读取单独一个的一列
                a[j]+=s[i];
            }
            i--;//一次循环结束了会i++,上面结束循环已经+1了,所以要-1
        }
        string tmp="";
        for(int i=0;i<numRows;i++){//把保存的字符串都放到tmp中
            tmp+=a[i];
        }
        return tmp;
    }
int main(){
	string a="LEETCODEISHIRING";
	cout<<convert(a,4);
	return 0;
} 
Published 14 original articles · Like 10 · Visitors 10,000+

Guess you like

Origin blog.csdn.net/Milan_1in/article/details/105447907