Leecode06. Zigzag Transformation -- leecode100 hot questions series

I'm Xiao Zhang , Determined to use the most concise code to do the most efficient expression


The following is my personal solution , Each problem includes all solutions as much as possible , And achieve the optimal solution , Welcome to collect ! Leaving a message. !

Portal ——>Leecode Big factory hot topic 100 Tao series problem solution


Problem description

Will a given string s According to the given number of rows numRows , From top to bottom 、 Left to right Z Font arrangement .

For example, the input string is “PAYPALISHIRING” The number of rows is 3 when , Arranged as follows :
 Insert picture description here
after , Your output needs to be read line by line from left to right , Generate a new string , such as :“PAHNAPLSIIGYIR”.
Please implement this function to transform a string into a specified number of lines :

string convert(string s, int numRows);

Example 1:
Input :s = “PAYPALISHIRING”, numRows = 3
Output :“PAHNAPLSIIGYIR”

Example 2:
Input :s = “PAYPALISHIRING”, numRows = 4
Output :“PINALSIGYAHRPI”

Example 3:
Input :s = “A”, numRows = 1
Output :“A”


The core idea

Looking for a regular , Optimize


Code

class Solution {

public:
int min(int a, int b) {

return a > b ? a : b;
}
string convert(string s, int numRows) {

string ss[min(numRows, s.length())]; // Take the minimum of the two 
bool flag = false;
int nowRow = 0, i = 0; // Current row 
while (i != s.length()) {

ss[nowRow] += s[i++];
if (nowRow == 0 || nowRow == numRows - 1) flag = !flag;
flag ? nowRow++ : nowRow--;
}
string res;
for(auto temp : ss) {

res += temp;
}
return res;
}
};

When you think you're smart , When everyone starts praising you , In fact, you are just harvesting your previous accumulation .

Please bring the original link to reprint ,thank
Similar articles

2021-10-14