6. Z 字形变换
这道题的链接: 6. Z 字形变换
今天搞到微软苏州一位小姐姐的内推,感觉好开心哈哈哈哈哈哈,和微软小姐姐交流感觉小姐姐素质很高,没有我遇到过的大多公司HR那么豪横,经过初筛以后简历过了,不过人家建议我刷够300道力扣中等题再来试试,会一直保留我的HC,那还说什么,整吧那就,刷就完事了。
一般我刚开始碰到这种故事题,我总是感觉一脸懵逼,这讲的是啥玩意,我看了半天我总感觉这个Z字形变换的话,我感觉这个不是Z,应该是N。。。妈个鸡,说白了就是下面这个样子
0 6 12 18ar
1 5 7 11 13 17
2 4 8 10 14 16
3 9 15
这才明显嘛。要不一下子真的看不出来,我去…
这道题的话,我们可以用最土的方法,借用一个正反变量,因为我们要拐弯,我们通过遍历字符串,然后按照字符串长度根据numRows和正反变量不断调整,进而实现
class Solution {
public String convert(String s, int numRows) {
if(numRows == 1){
return s;
}
boolean direction = false;
int curRow = 0;
List<StringBuilder> rowList = new ArrayList<>();
StringBuilder result = new StringBuilder();
for(int i = 0; i < numRows; i++){
rowList.add(new StringBuilder());
}
for (char temp : s.toCharArray()) {
rowList.get(curRow).append(temp);
if(curRow == 0 || curRow == numRows - 1){
direction = !direction;
}
curRow += direction ? 1 : -1;
}
for(StringBuilder temp : rowList) {
result.append(temp);
}
return result.toString();
}
}