leetcode【中等】6、Z字形变换

leetcode【中等】6、Z字形变换_第1张图片
leetcode【中等】6、Z字形变换_第2张图片
思路:字符串先a[0],a[1],a[2]…正序填入数组,到a[numRows-1]再倒叙排

leetcode【中等】6、Z字形变换_第3张图片

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows<2:
            return s
        a=[''for _ in range(numRows)]#先置空,不然后面会超出索引范围
        i=0#行号,0~numRows-1
        flag=-1#1为正序,-1为倒叙
        for c in s:
            a[i]+=c#填入第i行
            if i==0 or i==numRows-1:#表示该换列了
                flag=-flag
            i=i+flag
        return ("".join(a))
class Solution {
    public String convert(String s, int numRows) {
        if(numRows<2){
            return s;
        }

        int row=0;
        int flag=-1;
        List<StringBuilder>res=new ArrayList<>();
        for (int i = 0; i < Math.min(numRows, s.length()); i++)
            res.add(new StringBuilder());

        for (char c : s.toCharArray()) {
            res.get(row).append(c);
            if (row == 0 || row == numRows - 1){
                flag = -flag;
            } 
            row += flag;
        }

        StringBuilder res_s = new StringBuilder();
        for (StringBuilder r : res){
            res_s.append(r);
        } 
        return res_s.toString();
    }
}

你可能感兴趣的:(leetcode,leetcode,算法)