算法
学习yxc的算法
0 8 16 24
1 7 9 15 17 23 25
2 6 10 14 18 22
3 5 11 13 19 21
4 12 20
C++代码
class Solution {
public:
static string convert(const string &str, const int numRows) {
const int n = static_cast<int>(str.size());
if (numRows <= 1 || n <= numRows) {
return str;
}
const int offset = (numRows - 1) << 1;
string res(n, ' ');
int resI = 0;
for (int i = 0; i < numRows; ++i) {
if (i == 0 || i + 1 == numRows) {
for (int j = i; j < n; j += offset) {
res[resI++] = str[j];
}
} else {
for (int j = i, k = offset - i; j < n || k < n;
j += offset, k += offset) {
if (j < n) {
res[resI++] = str[j];
}
if (k < n) {
res[resI++] = str[k];
}
}
}
}
return res;
}
};
Java代码
class Solution {
public static String convert(final String str, final int numRows) {
final int n = str.length();
if (numRows <= 1 || n <= numRows) {
return str;
}
final StringBuilder res = new StringBuilder(n);
res.setLength(n);
int resI = 0;
final int offset = (numRows - 1) << 1;
for (int i = 0; i < numRows; ++i) {
if (i == 0 || i + 1 == numRows) {
for (int j = i; j < n; j += offset) {
res.setCharAt(resI++, str.charAt(j));
}
} else {
for (int j = i, k = offset - i; j < n || k < n; j += offset, k += offset) {
if (j < n) {
res.setCharAt(resI++, str.charAt(j));
}
if (k < n) {
res.setCharAt(resI++, str.charAt(k));
}
}
}
}
return res.toString();
}
}
Python3代码
class Solution:
def convert(self, s: str, numRows: int) -> str:
n = len(s)
if numRows <= 1 or n <= numRows:
return s
res = []
offset = (numRows - 1) << 1
for i in range(numRows):
if i == 0 or i + 1 == numRows:
for j in range(i, n, offset):
res.append(s[j])
else:
j = i
k = offset - i
while j < n or k < n:
if j < n:
res.append(s[j])
if k < n:
res.append(s[k])
j += offset
k += offset
return ''.join(res)
Go代码
func convert(str string, numRows int) string {
n := len(str)
if numRows <= 1 || n <= numRows {
return str
}
res := make([]byte, n)
resI := 0
offset := (numRows - 1) << 1
for i := 0; i < numRows; i++ {
if i == 0 || i+1 == numRows {
for j := i; j < n; j += offset {
res[resI] = str[j];
resI++
}
} else {
j := i
k := offset - i
for j < n || k < n {
if j < n {
res[resI] = str[j]
resI++
}
if k < n {
res[resI] = str[k]
resI++
}
j += offset
k += offset
}
}
}
return string(res)
}