ZigZag Conversion——LeetCode进阶路⑥

65 篇文章 1 订阅
60 篇文章 0 订阅

原题链接https://leetcode.com/problems/zigzag-conversion/

没开始看题目时,小陌发现这道题似乎备受嫌弃,被n多人踩了,还有点小同情

  • 题目描述

    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
  • 思路分析:
    题目需求是把输入字符排成锯齿牙子,再按行进行输出
    至于锯齿牙子啥样,没脑补出来的猿兄们看eg:
    Input: s = "123456789", numRows = 2
    1 3 5 7 9
    2 4 6 8

Output: "135792468"
Input: s = "123456789", numRows = 3
1     5   9
2  4 6 8
3     7

Output: "159246837"
Input: s = "123456789", numRows = 4
1       7
2    6 8
3 5    9
4


Output: "172683594"
恭喜猿兄,你已经把这道题中“最难”的部分搞定了,如你所见,除了题意相对难理解之外,剩下的简直就是数学的找规律问题
尔后猿兄也发现阿六为啥被踩了叭~
规律分析:(方便起见,n=numRows)

         
首尾两行元素之间的间隔interval1 = 2n-2

两者之间的行中元素的间隔interval = 前一元素的列数 + interval1 - 2 * 当前行数

  • 源码附录
    class Solution {
        public String convert(String s, int numRows) {
            if(s == null||numRows<=0){
                return "";
            }
            if(s.length()<2||numRows<2){
                return s;
            }
            
            int interval = 2*numRows - 2;
            int interval1;
            StringBuilder sb = new StringBuilder();
            for(int i=0;i<numRows;i++){
                for(int j=i;j<s.length();j=j+interval){
                    sb.append(s.charAt(j));
                    if(i != 0&&i != numRows-1){
                        interval1 = j + interval - 2*i;
                        if(interval1 < s.length()){
                            sb.append(s.charAt(interval1));
                        }
                    }
                }
            }
            return sb.toString();
        }
    }

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值