• 【LeetCode】6. Z 字形变换


    题目

    将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。

    比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:

    L   C   I   R  
    E T O E S I I G
    E   D   H   N  
     

    之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。

    示例 1:

    输入: s = "LEETCODEISHIRING", numRows = 3
    输出: "LCIRETOESIIGEDHN"


    示例 2:

    输入: s = "LEETCODEISHIRING", numRows = 4
    输出: "LDREOEIIECIHNTSG"

    解题

     初看这题没什么头绪,只要我们把字母转换数字(字符的位置)就能发现其中规律,下面是一个长度16,4行排列的例子
    0     6     12
    1   5 7   11 13
    2 4   8 10   14
    3     9     15
     
     
     
    题目就能转换为
    原来字符串        0 1 2 3 4 5 6 7 8 10 11 12 13 14 15
    转换后字符串    0 6 12 1 5 7 11 13 2 4 8 10 14 3 9 15
    上面例子两种情况
    1. 首行和尾行两个数字中间都是空
    2. 中间行两个数字间有且只有一个数字  
    首先想到按行读取,如果忽略有空位的列,规律还是很明显
    0 -> 6  6 -> 12
    1 -> 7  7 -> 13
    2 -> 8  8 -> 14
    3 -> 9  9 -> 15
    忽略空行,每个位置偏移6, offset = row * 2 - 2
    现在只要找到中间行两个数字间的数规律就能解这道题
    第2行   1 -> 5   7 -> 11   
    第3行   2  -> 4    8 ->10
    中间的数字 = i + (offset - 2 * i)
    代码如下
    public string Convert(string s, int numRows)
    {
        if (string.IsNullOrEmpty(s)) return s;
    
        if (numRows <= 1) return s;
    
        var offset = 2 * numRows - 2;
        var index = 0;
        var chars = new Char[s.Length];
    
        for (int i = 0; i < numRows; i++)
        {
            var subOffset = offset - 2 * i;
            for (int k = 0; (i + k) < s.Length; k += offset)
            {
                chars[index++] = s[i + k];
    
                if (i == 0 || i == numRows - 1) continue;
    
                if (i + k + subOffset < s.Length) chars[index++] = s[i + k + subOffset];
            }
        }
    
        return new String(chars);
    }
    View Code

         LeetCode 提交通过


     来源:力扣(LeetCode)

     链接:https://leetcode-cn.com/problems/zigzag-conversion/solution/z-zi-xing-bian-huan-by-leetcode/

  • 相关阅读:
    官网英文版学习——RabbitMQ学习笔记(四)Work queues
    官网英文版学习——RabbitMQ学习笔记(三)Hello World!
    官网英文版学习——RabbitMQ学习笔记(二)RabbitMQ安装
    微服务中springboot启动问题
    nodejs-mime类型
    nodejs-mime类型
    const isProduction = process.env.NODE_ENV === 'production'; 作用
    单向绑定
    建立Model
    使用Sequelize
  • 原文地址:https://www.cnblogs.com/WilsonPan/p/11757745.html
Copyright © 2020-2023  润新知