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 RAnd 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=1;j--)
{
if(i==len)
break;
sBuilder[j].append(s.charAt(i));
i++;
}
}
for(i=0;i
結果:
