Leetcode | ZigZag Conversion

Source: Internet
Author: User

Leetcode | ZigZag Conversion

Problem:

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

Thinking:

(1) read the meaning of the question, rearrange the strings according to the "Z" shape, and then output the strings by line link.

(2) There is no idea of disintegration. You can list a few simple examples to find a rule.

I. Sorting of 1 to n in two rows
1 3 5 7 9...
2 4 6 8 10...

Ii. Sorting of 1 to n in three rows
1 5 9...
2 4 6 8 10...
3 7 11...

Iii. Sorting of 1 to n in four rows
1 7 13...
2 6 8 12 14...
3 5 9 11 15...
4 10 16...

Is this rule true? If not, you can continue to write 5 rows. Soon you can find the rule. This is a solution to the problem. When we encounter a difficult problem, let's first consider the simple situation to see if we can find the rule. By writing out these special cases, we can find the following rule. Here we assume we are divided into m rows:
1. the I-th row starts with I.
2 The interval between two numbers in the I row is 2 (I-1), 2 (m-I) Alternate

Code:

class Solution {public:    string convert(string s, int nRows) {        int length = s.size();               if((nRows==1)||(nRows>=length))            return s;        string result;        for(int i=0;i
 
  

Related Article

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.