记录leetCode6: 一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列

/**
 *  Z 字形变换
 *
 * @author xiaofeifei
 * @date 2019-11-06
 * @since
 */
public class Solution1 {

    /**
     * ps:
     *   numRows = 3 ,s = abc d efg   3 - 2 = 1
     *
     *   a       e   => s[0] = a  s[4] = w          =>   0   numRows
     *
     *   b   d   f   => s[1] = b  s[3] = d  s[5] = f
     *
     *   c       g   => s[2] = c  s[6] = g
     *
     *
     *   numRow = 4, s= abcd e f ghij  4 - 2 = 2
     *
     *
     *   a        g  => s[0] = a  s[6] = g          => i = i + numRows + numRows - 2
     *
     *   b     f  h  => s[1] = b  s[5] = f  s[7] = h       => i = i + 2 * numRows - 2
     *
     *   c  e     i  => s[2] = c  s[4] = e  s[8] = i
     *
     *   d        j  => s[3] = d  s[9] = j
     *
     *  以下方法以遍历方向的方式将相关字符添加到对应的行
     *  0 -> numRows - 1 row++
     *  numRows - 1 -> 2(numRows - 1) row--
     *  2(numRows - 1) -> 3(numRows - 1) row++
     *
     *
     * @param s s的长度大于等于3
     * @param numRows
     * @return
     */
    public String convert(String s, int numRows) {

        if (numRows == 1) {
            return s;
        }
        if (s.length() <= numRows) {
            return s;
        }

        // 定义行数组
        StringBuilder[] rows = new StringBuilder[numRows];
        IntStream.range(0, numRows).forEach( t -> rows[t] = new StringBuilder());

        // 定义行索引
        int row = 0;

        // 行索引是否增加
        boolean isIncrease = false;

        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            rows[row].append(chars[i]);

            if (row == 0) {
                isIncrease = true;
            } else if (row == numRows - 1) {
                isIncrease = false;
            }
            if (isIncrease) {
                row++;
            } else {
                row--;
            }

        }


        return Stream.of(rows).reduce(StringBuilder::append).get().toString();
    }

    public static void main(String[] args) {
         String str = new Solution1().convert("ab", 1);

         System.out.println("str = " + str);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值