6. ZigZag Conversion

ZigZag Conversion

题目大意:

For example: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
while convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”

我的想法、

创建nRows 的StringBuffers,然后使用java中的append()函数依次追加字符串;

代码、

public class Solution {
    public String convert(String s, int numRows) {
        char[] c = s.toCharArray();  //变成数组
        int len = s.length();
        StringBuffers[] sb = new StringBuffers[numRows];  //实例化对象sb
        for(int i = 0; i < sb.length; i++)
            sb[i] = new StringBuffers();
        int i = 0;
        while(i < len){
            for(int j = 0; j < len && j<numRows; j++)
                sb[j].append(c[i++]);  //开始从上向下插入值
            for(int j = numRows - 2; j < len && j > 0; j--) //注意此处的numRows-2
                sb[j].append(c[i++]);  //插入对角线方向的值
        } 
    }
    for(int i = 1; i < numRows; i++)
            sb[0].append(sb[i]);   //进行每一行的依次的插入并输出
    return sb[0].toString;   //按照字符串的方式读出 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值