Z 字形变换

This commit is contained in:
LingZhaoHui 2020-11-18 21:55:34 +08:00
parent c14d9f3154
commit dd71ac5ee5
2 changed files with 104 additions and 0 deletions

21
hs_err_pid287213.log Normal file
View File

@ -0,0 +1,21 @@
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00007f215cc73133, pid=287213, tid=287228
#
# JRE version: OpenJDK Runtime Environment (11.0.9+11) (build 11.0.9+11-post-Debian-1)
# Java VM: OpenJDK 64-Bit Server VM (11.0.9+11-post-Debian-1, mixed mode, sharing, tiered, compressed oops, g1 gc, linux-amd64)
# Problematic frame:
# C [libjimage.so+0x3133]
#
# Core dump will be written. Default location: /home/zeek/project/leetCode/core
#
# If you would like to submit a bug report, please visit:
# https://bugs.debian.org/openjdk-11
#
--------------- S U M M A R Y ------------
Command Line: -agentlib:jdwp=transport=dt_socket,suspend=y,address=localhost:43579 -javaagent:/home/zeek/software/eclipse_java/configuration/org.eclipse.osgi/406/0/.cp/lib/javaagent-shaded.jar -Dfile.encoding=UTF-8 -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true com.leetcode.string.Convert2Zstr
Host:

View File

@ -0,0 +1,83 @@
package com.leetcode.string;
import java.util.ArrayList;
import java.util.List;
/**
*
Z 字形变换:
将一个给定字符串根据给定的行数以从上往下从左到右进行 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
著作权归领扣网络所有商业转载请联系官方授权非商业转载请注明出处
*
* @author zeek
*
*/
public class Convert2Zstr {
public String convert(String s, int numRows) {
if (numRows == 1) {
return s;
}
List<StringBuilder> rows = new ArrayList<>();
for (int i = 0; i < Math.min(numRows, s.length()); i++) {
rows.add(new StringBuilder());
}
int curRow = 0;
boolean goingDown = false;
for (char c : s.toCharArray()) {
rows.get(curRow).append(c);
if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
curRow += goingDown ? 1 : -1;
}
StringBuilder ret = new StringBuilder();
for (StringBuilder row : rows) {
ret.append(row);
}
return ret.toString();
}
public static void main (String args[]) {
Convert2Zstr conv = new Convert2Zstr();
String s = "LEETCODEISHIRING";
int numRows = 4;
String res = conv.convert(s, numRows);
System.out.println(res);
}
}