6. ZigZag Conversion

本文介绍了一种将字符串以Z形方式排列并按行读取的算法实现。提供了两种解决方案,一种通过跟踪当前行和方向变化,另一种利用周期性公式进行优化。这两种方法均实现了字符串的正确转换。

题目

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
And 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 s, int numRows);
Example :

Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
P I N
A L S I G
Y A H R
P I

我的思路

找到了周期(numRows∗2−2)(numRows*2 - 2)(numRows22),头行表示为k∗(numRows∗2−2)k*(numRows*2 - 2)k(numRows22)和尾行为k∗(numRows∗2−2)+(numRows−1)k*(numRows*2 - 2) + (numRows - 1)k(numRows22)+(numRows1)。但在斜边的规律不太一样,作罢。

解答

leetcode solution1: sort by row
用curRow和goingDown两个游标来控制。当curRow为第一行或最后一行时,goingDown反向,由此直接按照Z顺序将s分行存入list中,最后合并成一行。

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();
    }
}

leetcode solution2: visit by row
周期公式的解法,原来中间重叠的部分可以用两个公式来表达,iii为当前行
k∗(numRows∗2−2)+ik*(numRows*2 - 2) + ik(numRows22)+i(k+1)∗(numRows∗2−2)−i(k+1)*(numRows*2 - 2) - i(k+1)(numRows22)i
这样整个算法可以写为两个公式:
k∗(numRows∗2−2)+ik*(numRows*2 - 2) + ik(numRows22)+i
(k+1)∗(numRows∗2−2)−i(k+1)*(numRows*2 - 2) - i(k+1)(numRows22)i //表示斜边上的元素
虽说空间复杂度更低,但是没有solution 1更加便于理解

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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值