题目原型:
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"
.基本思路:
这道题我自己想了一种思路,完全是按照矩阵的路径来做的,虽说做出来了,但是比较笨重。
public String convert(String s, int nRows) { if(nRows==1) return s; if(nRows==2) { String s1 = ""; String s2 = ""; for(int index = 0;index<s.length();index++) { if(index%2==0) s1+=s.charAt(index); else s2+=s.charAt(index); } return s1+s2; } StringBuffer strbuf = new StringBuffer(); int row = 0; int column = 0; row = nRows; column = (nRows-1)*(s.length()/(nRows+(nRows-2))); if(s.length()%(nRows+(nRows-2))<=nRows) column+=1; else column=column+(s.length()%(nRows+(nRows-2))-nRows)+1; Character[][] ch = new Character[row][column]; int i = 0;//表示行 int j = 0;//表示列 int index = -1;//遍历字符串要用 int count = 0;//计数步数 for(;index<s.length()-1;) { //先向下走nRows步 count = nRows; while(count>0&&index<s.length()-1) { index++; ch[i][j] = s.charAt(index); i++; count--; } i--;//向上退回一步 //斜向上走nRows-2步 count = nRows - 2; while(count>0&&index<s.length()-1) { index++; i--; j++; ch[i][j] = s.charAt(index); count--; } i--; j++;//斜向上走到待定位置 } for(i=0;i<row;i++) { for(j=0;j<column;j++) { if(ch[i][j]!=null) strbuf.append(ch[i][j]); } } return strbuf.toString(); }
public String convert(String s, int nRows) { if (s == null || s.length() <= nRows || nRows <= 1) return s; StringBuffer sb = new StringBuffer(); // the first row for (int i = 0; i < s.length(); i += (nRows - 1) * 2) { sb.append(s.charAt(i)); } for (int i = 1; i < nRows - 1; i++) { for (int j = i; j < s.length(); j += (nRows - 1) * 2) { sb.append(s.charAt(j)); if (j + (nRows - i - 1) * 2 < s.length()) { sb.append(s.charAt(j + (nRows - i - 1) * 2)); } } } // the last row for (int i = nRows - 1; i < s.length(); i += (nRows - 1) * 2) { sb.append(s.charAt(i)); } return sb.toString(); }
ZigZag Conversion,布布扣,bubuko.com
原文:http://blog.csdn.net/cow__sky/article/details/20932175