Leetcode notes: ZigZag Conversion

Source: Internet
Author: User

I. Title Description

The string "Paypalishiring" is written with a zigzag pattern on a given number of rows like this: (You could want to display T His pattern in a fixed font for better legibility)

P   A   H   NII GY   I   R

And then read on line: "PAHNAPLSIIGYIR"
Write the code that would take a string and make this conversion given a number of rows:

String convert (string text, int nRows);
convert("PAYPALISHIRING", 3)should return "PAHNAPLSIIGYIR" .

Two. Topic analysis

This question is the relationship between the elements of the original string and the elements of the jagged string, and we can give an example to illustrate that assuming the original string of each character's subscript is 0,1,2,3, ..., 12 respectively, the number of rows for the 3,4,5 line is jagged.

Defines the original string to be aliased according to the NRows line, defining step= 2 * nRows-2; As can be seen from the above example, for line I, there are two situations:

1. For lines No. 0 and (nRows-1), the elements of each line are I, I+step, I+2*step,... ;
2. For other lines, the element for each row is I, step-i, i + Step, 2*step-i,...。

Three. Instance code

class Solution{public:string Convert(string s, int nRows){Const INTSize= S.size(); If(Size <= nRows)||(nRows = = 1)) {return s; } const INTStep= 2 * NROWS-2; StringResult; For(int RowIndex = 0; RowIndex < nRows; RowIndex+ +){intIndex=RowIndex; If((RowIndex = = 0)||(RowIndex = = (nRows -1))) {While(Index < Size){Result. push_back(s[Index]);Index=Index+Step;            } continue; } intSecondindex=Step-Index; While(Index < Size)||(secondindex < Size)) {if(Index < Size){Result. push_back(s[Index]);Index=Index+Step; } if(secondindex < Size){Result. push_back(s[secondindex]);Secondindex=Secondindex+Step; }}} returnResult; }};

Four. Summary

This problem is mainly to find the original string of the element coordinates and the jagged string after the coordinate relationship.

Leetcode notes: ZigZag Conversion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.