Java,LeetCode 6. Z 字形变换

字符串,Z 字形变换

1. 题目描述

难易度:中等

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

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

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

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

string convert(string s, int numRows);

示例 1:

输入: s = “LEETCODEISHIRING”, numRows = 3
输出: “LCIRETOESIIGEDHN”

示例 2:

输入: s = “LEETCODEISHIRING”, numRows = 4
输出: “LDREOEIIECIHNTSG”
解释:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zigzag-conversion

2. 思路分析

  1. 创建字符串数组arr
  2. 定义索引index,循环遍历字符串s
  3. 索引index从0增加到numRows,再从numRows减小到0
  4. 循环此操作,依次将遍历到的字符拼接到index所对应数组位置元素后
  5. 遍历arr,取出最终的结果
  6. 详细步骤见代码

3. 代码演示

/**
 * @Description TODO
 * @Author YunShuaiWei
 * @Date 2020/6/21 16:33
 * @Version
 **/
public class Solution {
    public static void main(String[] args) {
        Solution s = new Solution();
        String s1 = s.convert("ABC", 4);
        System.out.println("ABC".equals(s1));
    }

    public String convert(String s, int numRows) {
        if (s == null || numRows < 2 || s.length() < 3) {
            return s;
        }
        String[] arr = new String[numRows];
        int index = 0;
        //用于记录字符串s的索引
        int sIndex = 0;
        while (true) {
            for (int i = index; i < numRows && sIndex < s.length(); i++) {
                arr[i] += s.charAt(sIndex++);
                index++;
            }
            if (sIndex >= s.length()) {
                break;
            }
            index--;
            for (int i = index - 1; i > 0 && sIndex < s.length(); i--) {
                arr[i] += s.charAt(sIndex++);
                index--;
            }
            index--;
            if (sIndex >= s.length()) {
                break;
            }
        }
        String result = "";
        for (int i = 0; i < numRows; i++) {
            if (arr[i] != null) {
                //截取字符串,去掉前面索引0-4:null
                result += arr[i].substring(4, arr[i].length());
            }
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ysw!不将就

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值