StarryNights

每一个你所后悔的现在,都有一个不够努力的曾经

站内检索

循着字句,邂逅星光

搜索文章标题与正文,直达命中的章节

开始一次轻盈的站内探索

从这些主题开始探索

输入关键词

可同时输入多个词语缩小范围

发现内容

在摘要中查看高亮的关键词

快速直达

点击文章或章节标题继续阅读

# 引言

题目链接:https://leetcode.com/problems/zigzag-conversion/description/

# 题目大意

给出一个字符串, 和一个指定行数, 将字符串纵向按照z字形排列(指定行数为z字形大小)

  • Example

s = "PAYPALISHIRING", numRows = 3

Output: "PAHNAPLSIIGYIR"

Z字形排列图

P A H N
A P L S I I G
Y I R

# 题解

# 一句话题解

一个规律题, 按照Z字形排列图, 逐行扫描, 推断每一行下一个出现字母的索引的位置即可。

具体规律见图

ZigZagConversion

复杂度O(n)

# AC代码

c++版本

class Solution
{
  public:
    string convert(string s, int numRows)
    {
        int len = s.length();
        if (len <= 1 || len <= numRows || numRows <= 1)
        {
            return s;
        }
        char rStr[len + 1];
        memset(rStr, '\0', sizeof(rStr));
        for (int i = 0, j = 0; i < numRows; ++i)
        {
            int k = i;
            // 逐行扫描
            if (0 == i || numRows - 1 == i)
            {
                while (k < len)
                {
                    rStr[j++] = s[k];
                    k += (numRows - 1) * 2;
                }
            }
            else
            {
                while (k < len)
                {
                    rStr[j++] = s[k];
                    int h = k + (numRows - i - 1) * 2;
                    if (h < len)
                    {
                        rStr[j++] = s[h];
                    }
                    k += (numRows - 1) * 2;
                }
            }
        }
        return string(rStr);
    }
};

go版本

func convert(s string, numRows int) string {
    lens := len(s)
	if lens <= 1 || lens <= numRows || numRows <= 1 {
		return s
	}
	rStr := make([]byte, lens)
	index := 0
	for i := 0; i < numRows; i = i + 1 {
		k := i
		if  0 == i || numRows - 1 == i {
			for k < lens {
				rStr[index] = s[k]
				index = index + 1
				k = k + (numRows - 1) * 2
			}
		} else {
			for k < lens {
				rStr[index] = s[k]
				index = index + 1
				h := k + (numRows - i - 1) * 2
				if h < lens {
					rStr[index] = s[h]
					index = index + 1
				}
				k = k + (numRows - 1) * 2
			}
		}
	}
	return string(rStr)
}
更新于 阅读次数 — 次
STARRY NIGHTSPERSONAL NOTES

赞赏

文章至此,故事还在继续。

Seiun

长按或右键保存收款码

文章关联

1 篇关联

顺着引用的连线,读见篇章交错的脉络

展开关系图

拖动平移 · Ctrl / ⌘ + 滚轮缩放 · 点击节点阅读

当前文章引用本文
引用列表

引用本文1

  • LeetCode Programming
    AI 摘要

    本文是作者为缓解拖延、练习 Go 语言而开启的 LeetCode 刷题记录,兼作个人题解。文中先介绍 C++ 输入输出加速技巧,通过 ios::sync_with_stdio(false) 解除 C/C++ 流同步、cin.tie(nullptr) 解除 cin 与 cout 绑定来提升效率;随后汇总多道 LeetCode 题解,列出题号、题目、难度及链接,涵盖第1至32题等。

本文引用0

暂无

文章关联