博客
关于我
leetcode做题记录0006
阅读量:354 次
发布时间:2019-03-04

本文共 1438 字,大约阅读时间需要 4 分钟。

问题描述

给定一个字符串和一个整数numRows,要求将字符串中的字符按照特定规则排列成numRows行。每行的字符数等于numRows,字符顺序是从下到上,每次移动一行,遇到边界时改变方向。

思路

  • 问题分析:我们需要将字符串中的字符分成多行,每行包含numRows个字符,字符顺序是从下到上移动,每次移动一行,遇到顶部或底部时改变方向。

  • 解决思路

    • 创建一个数组来保存每一行的字符列表。
    • 使用方向变量来控制当前移动方向(上或下)。
    • 遍历字符串中的每个字符,根据当前方向和当前所在行来决定下一个字符的位置。
    • 当到达顶部或底部时,改变方向继续移动。
  • 算法选择:使用循环遍历字符串中的每个字符,并根据当前状态更新每一行的字符列表。

  • 复杂度分析:时间复杂度为O(n),其中n是字符串的长度,空间复杂度为O(n),用于存储每一行的字符列表。

  • 解决代码

    public class Solution {    public String convert(String s, int numRows) {        if (numRows == 1) {            return s;        }        StringBuilder[] sbs = new StringBuilder[numRows];        for (int i = 0; i < numRows; i++) {            sbs[i] = new StringBuilder();        }        int currentRow = 0;        int direction = 1; // 1表示向下,-1表示向上        for (char c : s.toCharArray()) {            sbs[currentRow].append(c);            if (currentRow == 0) {                direction = 1;            } else if (currentRow == numRows - 1) {                direction = -1;            }            currentRow += direction;        }        StringBuilder result = new StringBuilder();        for (int i = 0; i < numRows; i++) {            result.append(sbs[i]);        }        return result.toString();    }}

    代码解释

  • 初始化:检查numRows是否为1,如果是,直接返回原字符串。否则,创建一个大小为numRows的StringBuilder数组。

  • 循环填充字符:遍历字符串中的每个字符,根据当前行和方向决定字符的位置。当前行从0开始,方向初始为向下(1)。

  • 方向调整:当当前行达到顶部(0)或底部(numRows - 1)时,改变方向。

  • 构建结果:将每一行的StringBuilder内容合并到一个结果StringBuilder中,最后返回结果字符串。

  • 这个方法高效且直接,能够处理各种情况,包括字符串长度不足和行数变化。

    转载地址:http://krhe.baihongyu.com/

    你可能感兴趣的文章
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
    查看>>
    npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
    查看>>
    npm scripts 使用指南
    查看>>
    npm should be run outside of the node repl, in your normal shell
    查看>>
    npm start运行了什么
    查看>>
    npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
    查看>>
    npm 下载依赖慢的解决方案(亲测有效)
    查看>>
    npm 安装依赖过程中报错:Error: Can‘t find Python executable “python“, you can set the PYTHON env variable
    查看>>
    npm.taobao.org 淘宝 npm 镜像证书过期?这样解决!
    查看>>
    npm—小记
    查看>>
    npm上传自己的项目
    查看>>
    npm介绍以及常用命令
    查看>>
    NPM使用前设置和升级
    查看>>
    npm入门,这篇就够了
    查看>>
    npm切换到淘宝源
    查看>>