力扣(leetcode):Z字形变换

Z字形变换 题目: 将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。 Iuput: s = “PAYPALISHIRING”, numRows = 3 Output: “PAHNAPLSIIGYIR” 解释: P I N A L S I G Y A H R P I

思路:按Z字排列,就是要把原来按序排列的字符串变成另一种规律存起来,然后输出,找规律,我们找一个周期,例如PAYPAL看成一个周期,而周期长度,刚好是numRows*2 - 2。然后我们做一表看的更清楚。第一行是原来的位置,后一行是转为“Z"的位置。

P A Y P A L I S H I R I N G 0 1 2 3 4 5 6 7 8 9 10 11 12 13 1 2 3 4 3 2 1 2 3 4 3 2 1 2 * *

我们可以看到以六为周期,大于四,也就是numRows就是递减的,小于四,就是余数。所以,我们可以每一行用一个串来存,按规律存入后。再一一拼接。

class Solution {
          
   
    public String convert(String s, int numRows) {
          
   
        if(numRows == 1)
            return s;//返回原串
        String []stringArray = new String[numRows];
       Arrays.fill(stringArray,"");//初始化String类

        int period = numRows*2 - 2;
        //遍历原串,将每行字符输入进news中
        for(int i = 0;i < s.length();i++)
        {
          
   
            int mod = i % period;
            if(mod < numRows)
            {
          
   
                stringArray[mod] += s.charAt(i);
            }
            else
            {
          
   
                stringArray[period - mod] += s.charAt(i);
            }
        }
        //整合每一个String类
        StringBuffer result = new StringBuffer();
        for(String t:stringArray)
        {
          
   
            result.append(t);
        }
        return result.toString();
    }
}

参考于力扣题解的一个视频讲解,然后,其中的代码有个Array后忘记加了个s。

经验分享 程序员 微信小程序 职场和发展