Question 6 of leetcode -- zigzag Conversion

Source: Internet
Author: User

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   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)Shocould return"Pahnaplsiigyir".

After a string is represented in the font "of", it is combined by each line to output a new string.

I learned the O (n) algorithm in my blog.

Create nrows strings, copy the coordinates of S to each string, and use pushback. The output of the last append connection. The Code is as follows:

class Solution {  public:      string convert(string s, int nRows)      {              if (nRows <= 1 || s.length() < 2)              return s;            string *s_arr = new string[nRows];          int nCount = 2 * (nRows - 1);  // 每个循环的轮回 也就是 2倍的nRows - 2          for (int i = 0; i < s.length(); ++i)          {              s_arr[nRows - 1 -abs(nRows - 1 - (i%nCount))].push_back(s[i]);          }            string str_result;          for (int i = 0; i < nRows; ++i)              str_result.append(s_arr[i]);            return str_result;      }  };

Coordinate matching is the key, and the logic thinking of mathematics is indeed strong. You can give an example of four rows.

Question 6 of leetcode -- 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.