1. Title Description
Arrange a given string s in zigzagging from top to bottom and left to right, numRows, according to the given number of rows.
For example, if the string “PAYPALISHIRING” is set to 3 rows, it will look like this:
PAHNAPLSIIGYIR Then your output needs to be read line by line from left to right, producing A new string, such as “PAHNAPLSIIGYIR”.
Implement this function to convert a string to the specified number of lines:
string convert(string s, int numRows);
Example 1:
Enter: s = “PAYPALISHIRING”, numRows = 3 Output: “PAHNAPLSIIGYIR” Example 2: Enter: S = “PAYPALISHIRING”, numRows = 4 Output: “PINALSIGYAHRPI” explanation: PINALSIGYAHRPI
Input: s = “A”, numRows = 1 output: “A”
Tip:
1 <= s.length <= 1000 s Consists of lowercase and uppercase letters,’,’, and ‘.’. 1 <= numRows <= 1000
Source: LeetCode link: leetcode-cn.com/problems/zi… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
Second, complete code
public class Solution {
public static void main(String[] args) {
String s = "PAYPALISHIRING";
int numRows = 3;
String value = convert(s, numRows);
System.out.println(value);
}
public static String convert(String s, int numRows) {
int s_length = s.length();
String result = "";
String str_array[] = new String[numRows];
if (s_length == 0 || numRows < 1) {
return s;
}
if (numRows == 1) {
return s;
}
for (int i = 0; i < s_length; i++) {
int divide_num = i / (numRows - 1);
int surplus_num = i % (numRows - 1);
if (divide_num % 2= =0) {
str_array[surplus_num] = (str_array[surplus_num] == null ? "" : str_array[surplus_num]) + s.charAt(i);
}
if (divide_num % 2! =0) {
str_array[numRows - surplus_num - 1] = (str_array[numRows - surplus_num - 1] = =null ? "" : str_array[numRows - surplus_num - 1]) + s.charAt(i); }}for (int i = 0; i < numRows; i++) {
if(str_array[i] ! =null)
result += str_array[i];
}
returnresult; }}Copy the code