目录
频道首页
算法进修——力扣0006 N字形变换
收藏
0
Aubyn 最近修改于 2023-11-01 23:38:49

N字形变换

难度:中等

题目描述

将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。 比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:

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

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"。 请你实现这个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);

示例1

输入:s = "PAYPALISHIRING", numRows = 3 输出:"PAHNAPLSIIGYIR"

示例2

输入:s = "PAYPALISHIRING", numRows = 4 输出:"PINALSIGYAHRPI"

示例3

输入:s = "A", numRows = 1 输出:"A"

题解

对每一个字符进行标记,将所得的字符所对应的行数记录到一个数组中,创建一个字典,对每一行存储的字符串进行拼接,之后输出

想法代码

using System.Text;

class Solution
{
    public static void Main(String[] args)
    {
        string s = "PAYPALISHIRING";
        Console.WriteLine(Convert(s,3));
    }

    public static string Convert(string s, int numRows)
    {
        int len = s.Length;
        int[] row = new int[len];
        int k = 1, f = 1, cnt = 0;
        while (cnt < len)
        {
            row[cnt++] = k;
            k += f;
            if (k == 1 || k == numRows) f *= -1;
        }
        Dictionary<int, StringBuilder> map = new Dictionary<int, StringBuilder>();
        for (int i = 0; i < len; i++)
        {
            if (!map.ContainsKey(row[i]))
            {
                map.Add(row[i], new StringBuilder(""));
            }
            map[row[i]].Append(s[i]);
        }
        StringBuilder ans = new StringBuilder("");
        foreach (var i in map)
        {
            ans.Append(i.Value);
        }
        return ans.ToString();
    }
}
内容大纲
批注笔记
算法进修——力扣0006 N字形变换
ArticleBot
z
z
z
z
主页
会议室
Git管理
文章
云文档
看板