Leetcode_6_ZigZag Conversion, leetcode_6_zigzag

Source: Internet
Author: User

Leetcode_6_ZigZag Conversion, leetcode_6_zigzag
Description:

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

After thinking for a long time, thinking is always limited to two-dimensional arrays, looking for a certain relationship between the length of the string and the number of rows and columns of two-dimensional arrays, thinking for a long time, no idea.

Then I went online and looked at it. There was a way of saying that I could use a string array. I thought of StringBuilder. How good is direct Append? How advanced is it than a two-dimensional array! Then we use StringBuilder to solve this problem.

Code:

public String convert(String s, int nRows) {        if(s==null)        return null;        else if (s.equals(""))        return "";        int len=s.length();        StringBuilder resultBuilder=new StringBuilder();        StringBuilder []sBuilder=new StringBuilder[nRows];        for(int i=0;i<nRows;i++)        sBuilder[i]=new StringBuilder();        int i=0,j=0;        while(i<len)        {        for(j=0;j<nRows;j++)        {        if(i==len)        break;        sBuilder[j].append(s.charAt(i));        i++;        }        for(j=nRows-2;j>=1;j--)        {        if(i==len)        break;        sBuilder[j].append(s.charAt(i));        i++;        }        }        for(i=0;i<nRows;i++)        resultBuilder.append(sBuilder[i]);        return resultBuilder.toString();    }


Result:



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.