In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
Xiaobian to share with you how leetcode to solve the zigzag transformation problem, I hope you have something to gain after reading this article, let's discuss it together!
Title Link
https://leetcode-cn.com/problems/zigzag-conversion/
Title Description
Zigzag a given string from top to bottom and from left to right according to the number of rows.
For example, when the input string is "LEETCODEISHIRING" and the number of rows 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, producing a new string, such as: "LCIRETOESIIGEDHN."
Please implement this function that transforms a string into a specified number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "LEETCODEISHIRING", numRows = 3
Output: "LCIRETOESIIGEDHN"
Example 2:
Input: s = "LEETCODEISHIRING", numRows = 4
Output: "LDREOEIIECIHNTSG"
Explanation:
L D R
E O E I I
E C I H N
T S G
solution train of thought
Tag: string
The overall idea is to traverse the string, and in the traversal process, each line is regarded as a new string to form a string array, and finally the array can be spliced together.
If numRows=1, then the current string is the result, return directly
Otherwise, the whole string needs to go through a loop of down to right, down to right, and so on. Set the down variable to indicate whether it is down, and the loc variable to indicate the index of the current string array.
If down is true, loc+=1, string array subscripts move backward, adding the current character to the current string
If down is false, it means right, loc-=1, string array subscript moves forward, adds current character to current string
Time complexity: O(n), n is the length of string s
code
Java version
class Solution {
public String convert(String s, int numRows) {
if(numRows == 1)
return s;
int len = Math.min(s.length(), numRows);
String []rows = new String[len];
for(int i = 0; i< len; i++) rows[i] = "";
int loc = 0;
boolean down = false;
for(int i=0;i
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.