问题说明:
给定字符串“ 前开发者教程”,行数为3。以Z字形模式编写字符串。
例:
Input: string = “prodevelopertutorial”. Number of rows 3
输出:
array output should be: "peotrrdvlpruoiloeeta"
以锯齿形方式可视化书写元素:
在数组中写入输出的可视化:
通过获取索引的数组元素的之字形模式将类似于:
0 4 8 12 16 1 3 5 7 9 11 13 15 17 19 2 6 10 14 18
我们可以借助“间隔”和“步”。关系如下图所示。
间隔 是两条垂直线之间的差。
A 步 是垂直线中间元素之间的差。
在我们的示例中
Interval between the 2 vertical column is 4. i.e 4 – 0 = 4, or 8 – 4 = 4 Step is 3 -1 = 2, 7 -5 = 2.
因此,我们可以得出一个公式的结论,如下所示:
间隔 = 2n – 2. Where n is number of rows Step = 间隔 – 2i. where “i” is the index.
算法的工作:
One for loop for each row For each row, calculate the 步. Then for each character in that row, we place it in correct vertical columns. [From the diagram, we know that for each column, the numbers increment sequentially except for the middle element.] if we find a correct middle element, place it correctly.
该算法的时间复杂度将为O(n)。许多人会感到困惑,因为我们使用2 for循环,时间复杂度为O(n ^ 2)。但是,如果您正确地遵循该解决方案,我们将只访问每个节点一次,并且不再重复。
C ++解决方案
#include<iostream> #include <string> using namespace std; void zigzagConvert(string input_string, int num_of_rows) { int 步 = 0; // to hold calcualted 步 value int 间隔 = 0; // to hold calcualted 间隔 value int i = 0; // for outer for loop int j = 0; // for inner for loop int lenghtOfString = input_string.size(); // get the lenght of the string string output_string; // to hold output string int count = 0; // for counting number of characters in output string if (num_of_rows <= 1 || num_of_rows > input_string.size()) { cout<< endl<< input_string <<endl; return; } interval = 2 * num_of_rows - 2; //calculate size of 间隔 for (i = 0; i < num_of_rows; ++i) // for each element in a row { step = 间隔 - 2 * i; // calculate 步 for each row as it is dependent 上 index for ( j = i; j < lenghtOfString; j+= 间隔) // place the element in the correct column { output_string += input_string [j]; count ++; // get the middle element if(step > 0 && 步 < 间隔 && j + 步 < lenghtOfString) { output_string += input_string[ j + 步]; count++; } } } cout<< endl<< "The input string is = "<<input_string <<endl; cout<< endl<< "The result is = "<<output_string <<endl; } int main() { string input_string = "前开发者教程"; int num_of_rows = 3; zigzagConvert(input_string, num_of_rows); //convert(input_string, num_of_rows); return 0; }
输出:
The input string is = 前开发者教程 The result is = peotrrdvlpruoiloeeta
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |