zoukankan      html  css  js  c++  java
  • letcodeZ字抖动

    题目

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

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

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

    请你实现这个将字符串进行指定行数变换的函数:

    string convert(string s, int numRows);

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/zigzag-conversion
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    解题思路

    
    public String convert(String s, int numRows) {
            if (numRows == 1) return s;
            int step = numRows + numRows - 2;
            int index = 0;
            int stepNum = s.length() / step;
            // 用数组保存结果,顺序存储快
            char[] resultArr = new char[s.length()];
            char[] tempArr = s.toCharArray();
            for (int i = 0; i < numRows; i++) {
                for (int j = 0; j <= stepNum; j++) {
    				// 逐行遍历并计算位置
                    int K = i + j * step;
                    if (K < s.length()) {
                        resultArr[index++] = tempArr[K];
                    }
    				// 除第一行和最后一行外,每步需要算两次位置
                    int L = i + j * step + step - 2 * i;
                    if (i != 0 && i < numRows - 1 && L < s.length()) {
                        resultArr[index++] = tempArr[L];
                    }
                }
            }
            return new String(resultArr);
        }
    
  • 相关阅读:
    php curl getinfo
    php 实现树形结构
    E时代主机,其实做一个小虚拟主机还是不错的
    php 生成验证码
    php curl
    nodejs 操作mysql
    php ++a和a++
    nodejs上传图片并显示的例子
    json
    Rock,Paper,Scissors 水NOJ 1090
  • 原文地址:https://www.cnblogs.com/bokers/p/15620710.html
Copyright © 2011-2022 走看看