Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use leetcode to realize Z-shape Transformation in golang

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

How to use leetcode to realize glyph transformation in golang? in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

Z-arranges a given string from top to bottom and left to right based on a given number of lines.

For example, if the input string is "LEETCODEISHIRING" and the number of lines is 3, the arrangement is as follows:

L C I R

E T O E S I I G

E D H N

After that, your output needs to be read line by line from left to right to produce a new string, such as "LCIRETOESIIGEDHN".

Please implement this function that converts a string to a specified number of lines:

String convert (string s, int numRows)

Example 1:

Enter: s = "LEETCODEISHIRING", numRows = 3

Output: "LCIRETOESIIGEDHN"

Example 2:

Enter: s = "LEETCODEISHIRING", numRows = 4

Output: "LDREOEIIECIHNTSG"

Explanation:

L D R

E O E I I

E C I H N

T S G

Ideas for solving the problem:

1, for letters, graphics, we can not find the rules intuitively, we use index to represent the graphics, it is easy to find the rules

2, for example 1 is available

0 4 8

1 3 5 7 9

2 6 10

For example 2, available

0 6 121 5 7 11 132 4 8 10 143 9 15

3, we can get the following rule (assuming the index of the letter in the string is I)

A, for each complete column (the column containing the number of numRows), the row index of the data is I% (2*numRows-2)

B, for incomplete column data, we first save it to a map that temporarily contains 2*numRows-2 column data, as follows:

0 4 8

1 5 9

2 6 10

3 7 / / I% (2*numRows-2) > = numRows

C, convert the above temporary map into the final map. For the data of I% (2*numRows-2) > = numRows, move to the next column, the numRows-2-j%numRows position of the next column, and the transformation is completed.

Detailed code

Func convert (s string, numRows int) string {if numRows

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report