【LeetCode】006.ZigZag Conversion

来源:互联网 发布:win10怎么装mac系统 编辑:程序博客网 时间:2024/05/22 13:04

题目如下:

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"


解答:

解答这道题需要仔细观察。想象为nRows层楼,每层一个住户等待收快递,快递小哥(好比圣诞老人),乘坐电梯,从1层到nRows层,每次1层,每层发一个包裹,到顶层后再往下发,依次类推,直到发完为止。加入快递发的是字符串,每次发1个字符,发完后,从顶至底的住户把收到的字符快递连接在一起,就得到了ZigZag Conversion。


有一个细节还需要注意,如果nRows等于1,就不必再处理了。代码实现时处理不当会导致异常。

代码如下:

public class Solution {    public String convert(String s, int nRows) {        if(nRows == 1) return s; // in case ArrayIndexOutBoundExceptionArrayList<String> als = new ArrayList<String>();int ind = -1,tag = 1;for(int i=0;i<nRows;i++){als.add(new String(""));}for(int i=0;i<s.length();i++){ind += tag;String cur = als.get(ind).concat(s.substring(i, i+1));als.set(ind, cur);if(ind == nRows - 1)tag = -1;else if(ind == 0){tag = 1;}}String ret = "";for(int i=0;i<als.size();i++){ret = ret.concat(als.get(i));}return ret;}}


0 0
原创粉丝点击