leetcode_6_ZigZag Conversion,leetcode_6_zigzag

來源:互聯網
上載者:User

leetcode_6_ZigZag Conversion,leetcode_6_zigzag
描述:

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) should return "PAHNAPLSIIGYIR".
思路:

想了好久,思維總是局限在二維數組,找字串的長度和二維數組的行列數之間的某種聯絡,想了好久,沒有思路。

然後,然後就上網看了一下,有一種思路說是用字串數組即可,就想到了StringBuilder,直接Append多好,這得比二維數組進階多少啊!然後就用StringBuilder做這道題了。

代碼:

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();    }


結果:



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.