标签:size substring build bst builder get integer var lis
这道题比较简单,观察清楚规律后很快可以写出来。
但是用go写的版本,总是答案错误,本地无问题。后用Java重写。
func convert(s string, numRows int) string {
if numRows == 1 {
return s
}
numChars := make(map[int][]string)
size := 2 * numRows - 2
for i := 0; i<len(s); i++ {
x := s[i : i+1]
if i % size < numRows {
row := i % size
numChars[row] = append(numChars[row], x)
} else {
row := size - i % size
numChars[row] = append(numChars[row], x)
}
}
var result string
for _, ss := range numChars {
for _, c := range ss {
result += c
}
}
return result
}
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1 || s == null) {
return s;
}
Map<Integer, List<String>> numChars = new HashMap<Integer, List<String>>();
int size = 2 * numRows - 2;
for (int i = 0; i < s.length(); i++) {
String x = s.substring(i, i + 1);
int row;
if (i % size < numRows) {
row = i % size;
} else {
row = size - i % size;
}
if (numChars.get(row) == null) {
numChars.put(row, new ArrayList<String>());
}
numChars.get(row).add(x);
}
StringBuilder result = new StringBuilder();
for (List<String> ss : numChars.values()) {
for (String c : ss) {
result.append(c);
}
}
return result.toString();
}
}
标签:size substring build bst builder get integer var lis
原文地址:https://www.cnblogs.com/yx1989/p/10986619.html