题目:Z字形变换(题目来自力扣网,用Java解决)
题目描述:
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
L C I R
E T O E S I I G
E D H N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"
示例 2:
输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"
解释:
L D R
E O E I I
E C I H N
T S G
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zigzag-conversion
class Solution {
public String convert(String s, int numRows) {
if (s == null || s.equals("") || s.length()<=1 || numRows<=1)
return s;
else {
int n = numRows;
int temp = s.length() / (n + n - 2);
if ((s.length() % (n + n - 2)) / n == 0)
temp = temp * (n - 1) + (s.length() % (n + n - 2)) % n;
else
temp = temp * (n - 1) + 1 + (s.length() % (n + n - 2)) % n;
String str[][] = new String[n][temp];
// System.out.println(temp);
int temp1 = 0;
int id = 0;
int i = 0;
int j = 0;
while (id < s.length()) {
// System.out.println(i+" "+j);
if (temp1 == 0) {
str[i][j] = String.valueOf(s.charAt(id));
id++;
if (i == n - 1) {
i--;
j++;
temp1 = 1;
} else
i++;
} else {
str[i][j] = String.valueOf(s.charAt(id));
id++;
if (i == 0) {
i++;
temp1 = 0;
} else {
i--;
j++;
}
}
}
String ss = "";
for (int l = 0; l < n; l++) {
for (int k = 0; k < temp; k++) {
if (str[l][k] == null)
continue;
else
ss += str[l][k] + "";
}
}
return ss;
}
}
}