首页 > 代码库 > leetcode_6_ZigZag Conversion

leetcode_6_ZigZag Conversion

描述:

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   N
A P L S I I G
Y   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();
    }


结果:

技术分享


leetcode_6_ZigZag Conversion