LeetCode 6. ZigZag Conversion

LeetCode 6. ZigZag Conversion

Description

在这里插入图片描述

Example

在这里插入图片描述

Code

  • java
class Solution {
    public String convert(String s, int numRows) {
        if(numRows < 2 || s == null || s.length() == 0) return s;
        int len = s.length();
        int loop = 2*numRows-2;
        int cols = len % loop == 0 ? len / loop : len / loop + 1;
        cols *= (numRows-1);
        char[][] str = new char[numRows][cols];
        for(int i = 0; i < numRows; i++) {
            for(int j = 0; j < cols; j++) {
                str[i][j] = ' ';
            }
        }
        int i = 0, j = 0;
        int cnt = 0;
        while(cnt < len) {
            if(i == 0) {
                for(; cnt < len && i < numRows; i++) {
                    str[i][j] = s.charAt(cnt++);
                }
                i-=2;
                j++;
            } else {
                str[i][j] = s.charAt(cnt++);
                i--;
                j++;
            }
        }
        StringBuilder sb = new StringBuilder();
        for(i = 0; i < numRows; i++) {
            for(j = 0; j < cols; j++) {
                if(str[i][j] != ' ') {
                    sb.append(str[i][j]);
                }
            }
        }
        return sb.toString();
    }
}
  • Official Solution
class Solution {
    public String convert(String s, int numRows) {

        if (numRows == 1) return s;

        List<StringBuilder> rows = new ArrayList<>();
        for (int i = 0; i < Math.min(numRows, s.length()); i++)
            rows.add(new StringBuilder());

        int curRow = 0;
        boolean goingDown = false;

        for (char c : s.toCharArray()) {
            rows.get(curRow).append(c);
            if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
            curRow += goingDown ? 1 : -1;
        }

        StringBuilder ret = new StringBuilder();
        for (StringBuilder row : rows) ret.append(row);
        return ret.toString();
    }
}
  • Official Solution2
class Solution {
    public String convert(String s, int numRows) {

        if (numRows == 1) return s;

        StringBuilder ret = new StringBuilder();
        int n = s.length();
        int cycleLen = 2 * numRows - 2;

        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j + i < n; j += cycleLen) {
                ret.append(s.charAt(j + i));
                if (i != 0 && i != numRows - 1 && j + cycleLen - i < n)
                    ret.append(s.charAt(j + cycleLen - i));
            }
        }
        return ret.toString();
    }
}

Conclusion

  • 还是要仔细找规律
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值