#6 ZigZag Conversion

Description

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)

And then read line by line: “PIN YLSIG YAHR PI”

Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);

Examples

Example1

Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”

Example2

Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”

解题思路

就是数学原理
以题目给出的例子为例,把字母转换成字符所在位置可以得到:

根据上表可以得出规律:
每两个颜色相同的块相差得值都一样,且都与numRows有关,差值 = 2 * numRows - 2
那接下来就很好做了
直接附上java代码

class Solution {
    public String convert(String s, int numRows) {
        if(numRows == 1)
            return s;
        int i, j, k;
        String add, final_str = "";
        ArrayList<String> temp = new ArrayList<>();
        for(i = 0; i < numRows; i++){
            add = "";
            for(j = i; j < s.length();){
                add += s.charAt(j);
                j += numRows * 2 - 2;
            }
            temp.add(add);
        }
        for(i = 1; i < numRows - 1; i++){
            int start = 2 * numRows - 2 - i;
            k = 1;
            for(j = start; j < s.length();){
                temp.set(i, InsertString(k, temp.get(i), s.charAt(j)));
                k += 2;
                j += numRows * 2 - 2;
            }
        }
        for(i = 0; i < temp.size(); i++){
            final_str += temp.get(i);
        }
        return final_str;
    }
    public String InsertString(int pos, String str, char ch){
        String ret;
        ret =  str.substring(0, pos) + ch;
        if(pos < str.length()){
            ret += str.substring(pos, str.length());
        }
        return ret;
    }
}

其他

需要注意的是:

  • 当numRows = 1的时候,需要单独考虑,否则会在判断得时候出错(2 * 1 - 2 = 0,j不会更新)
  • substring(i, j)中,i是可以取到的,而j是不能取到的
  • 在solution中提到了StringBuffer的使用,我不太清楚,等之后看懂了再来更新
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值