LeetCode之6_ZigZag Conversion

来源:互联网 发布:瞩目视频会议软件 编辑:程序博客网 时间:2024/05/16 08:50

题目原文:

 

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".

Subscribe to see which companies asked this question

 

分析:给出一个字符串,按照给定的行数进行N字形排序后,返回按照行遍历组成的新字符串。

           解法较简单,拆分为nRows个队列后依次进行入队列,注意首尾两个位置的特殊情况。

 

代码:

 

//Zigzag:即循环对角线结构(////   0       8        16       //   1     7 9     15 17       //   2   6   10   14  18       //   3 5     11 13    19       //   4       12       20       //#include <iostream>#include <string>using namespace std;class Solution {public:string convert(string s, int numRows) {if (numRows <= 0 || numRows == 1){return s;}string *sArr = new string[numRows];int nStepLen = 1;int nNowLoc = 0;int nLength  = s.length();for (int i = 0; i< nLength; i++){sArr[nNowLoc] += s.substr(i,1);nNowLoc += nStepLen;if (nNowLoc == 0 || nNowLoc == numRows-1){nStepLen = nStepLen*(-1);}}string strRet;for (int i =0 ;i<numRows; i++){strRet += sArr[i];}return strRet;}};


 

 

 

0 0