6. ZigZag Converesion 之字型转换字符串

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 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I

一道数学题目,如下

1           7               13
2      6   8       12    14        18
3    5     9    11       15   17
4          10              16

第一行与最后一行:等差数列,公差为(numRows - 1) * 2等差数列,公差为(numRows - 1) * 2
其他行:以第一个为准,偶数位置与上一个数字的差为(numRows - line -1) * 2,奇数位置与上一个数字差为line * 2;相当于往下走一个来回,得到一个数,再往上走一个来回,得到下一个。以此循环

class Solution {
        public String convert(String s, int numRows) {
            String ans = "";
            if (s.isEmpty() || numRows == 1)
                return s;
            int line = 0;
            while (line < numRows) {
                int cur = line;
                //先把行首字母放入
                if (cur < s.length()){
                    ans += String.valueOf(s.charAt(cur));
                }
                while (cur < s.length()){
                    //当该行是首行或末行的时候,两个数字之间的差为(numRows - 1) * 2
                    if (line == 0 || line == numRows -1){
                        cur += (numRows - 1) * 2;
                        if (cur < s.length()){
                            ans += String.valueOf(s.charAt(cur));
                        }
                    } else{
                    //不是首行或者末行,想往下走一个来回,得到下一个数
                        cur += (numRows - line -1) * 2;
                        if (cur < s.length()){
                            ans += String.valueOf(s.charAt(cur));
                        }
                    //再往上走一个来回
                        cur += line * 2;
                        if (cur < s.length()){
                            ans += String.valueOf(s.charAt(cur));
                        }
                    }
                }
                line++;
            }
            return  ans;
        }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值