将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入:s = “PAYPALISHIRING”, numRows = 3
输出:“PAHNAPLSIIGYIR”
示例 2:
输入:s = “PAYPALISHIRING”, numRows = 4
输出:“PINALSIGYAHRPI”
示例 3:
输入:s = “A”, numRows = 1
输出:“A”
class Solution {
public String convert(String s, int numRows) {
if(numRows == 1){
return s;
}
StringBuilder ret = new StringBuilder();
int len = s.length();
int cyclen = numRows*2 - 2;
for(int i = 0;i < numRows;i++){
for(int j = 0;j + i < len;j+=cyclen){
ret.append(s.charAt(j+i));
if(i != 0 && i != numRows-1 && j + cyclen -i < len){
ret.append(s.charAt(j+cyclen-i));
}
}
}
return ret.toString();
}
}
时间复杂度:O(n),虽然是两层循环,但第⼆次循环每次加的是cyclen ,⽆⾮是把每个字符遍历了 1次,所以两层循环内执⾏的次数肯定是字符串的⻓度。
空间复杂度:O(n),保存字符串
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/15787.html