LeetCode OJ 06 ZigZag Conversions

来源:互联网 发布:淘宝商品质检报告 编辑:程序博客网 时间:2024/06/01 08:07

题目难度:easy

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   NA P L S I I GY   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 text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".


思路: 刚入手题目的时候可能会不太理解题目的内容。ZigZag pattern的意思就是假设原字符串为01234556789。当row为3时,该字符串中元素的放置样式如图1所示;当row为4时,该字符串中元素的放置样式如图2所示。


输出的字符串顺序就是将这样放置的元素横向输出出来。


通过数学规律发现:第一行和最后一行两个元素的坐标差值为2*numRows-2

                              中间行差值为2*numRows-2的两个元素之间会多加一个元素,而这个元素坐标与前元素坐标差值为j+2*numRows-2-2*i  (其中j为前元素坐标而i为行数)



代码如下:

class Solution {public:    string convert(string s, int numRows) {        string output="";int zigPan = 2*numRows-2;int len = s.length();if(len<=2||numRows<2||len<numRows) return s;for(int i=0;i<numRows;i++){for(int j=i;j+numRows<len;j+=(zigPan+1)){output.push_back(s[j]);if(i!=0&&i!=(numRows-1)&&(j+2*numRows-2-2*i)<len){output.push_back(s[j+2*numRows-2-2*i]);}}}return output;    }};

性能分析:



0 0
原创粉丝点击