您的位置:首页 > 其它

leetcode小白解题记录——第六题

2016-09-14 20:29 453 查看
6. ZigZag ConversionThe string 
"PAYPALISHIRING"
 is written in a zigzag pattern on a given number of rows likethis: (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"
convert("PAYPALISHIRING",
3)
 should return 
"PAHNAPLSIIGYIR"
.
ZigZag:
这个问题在leetcode里面是简单的,我们住需要把字符串拆成numRows行,存成三行的字符数组就可以了。public class Solution {public String convert(String s, int numRows) {//主要利用字符串的拼接 +int len=s.length();if(len==0 || len==1 || numRows==1) return s;String[] ans=new String[numRows];//给字符串赋值Arrays.fill(ans, "");int row=0;int a=1;for(int i=0;i<len;i++){ans[row]+=s.charAt(i);row+=a;if(row>=numRows){row=row-2;a=-1;}if(row<0){row=1;a=1;}}//将 ans 的每一行拼接起来String str=new String();for(int j=0;j<numRows;j++){str+=ans[j];}return str;}}
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: