[Java]leetcode6 ZigZag Conversion

Source: Internet
Author: User

The string is "PAYPALISHIRING" written with 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 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".

Test instructions is: give you a string, he is the string in the form of a Z-order, and then you read it in the form of a line. The number of rows given the string.

Problem solving: We find that the first and last lines are well handled, that is, each time you read j+2*nrows-2, the middle row needs to be handled separately.

As the above example, we found that we can process each constituency PAYP as a unit. is to choose a nrows+nrows-2=2nrows-2 length processing.

Then the positional relationship of the middle element is j+2*nrows-2i-2 (i means the first few lines)

OK, the code is as follows:

Public String Convert (string s, int nRows) {if (s = = NULL | | nRows = = 1) return s;int len = s.length (); if (len <= nRows) r Eturn s; StringBuffer res = new StringBuffer (); int size = 2 * nrows-2;//length of each processing for (int i = 0; i < nRows; i++) {//element of each row char C h;for (int j = i; J < len; j + = size) {ch = S.charat (j); res.append (ch); if (i! = 0 && I! = nRows-1) {//If it is an intermediate element Processing int tmp = j + size-2 * I;IF (tmp < len) {ch = s.charat (TMP); res.append (ch);}}} return res.tostring ();}


[Java]leetcode6 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.