第六题:Z字形变换【leetcode】
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。比如输入字符串为 'LEETCODEISHIRING' 行数为 3 时,排列如下:
LCIRETOESIIGEDHN之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:'LCIRETOESIIGEDHN'。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
输入: s = 'LEETCODEISHIRING', numRows = 3
输出: 'LCIRETOESIIGEDHN'
输入: s = 'LEETCODEISHIRING', numRows = 4
输出: 'LDREOEIIECIHNTSG'
难度:中等
链接:https://leetcode-cn.com/problems/zigzag-conversion
var convert = function(s, numRows) {
let arr = Array(numRows);
let count = 0;
let isAsc = true;
for(let i = 0, l = s.length; i < l; i++){
if(arr[count]){
arr[count] = arr[count] + s[i];
}else{
arr[count] = s[i];
}
if(isAsc){
count++;
if(count == numRows - 1){
isAsc = false;
}
}else{
count--;
if(count == 0){
isAsc = true;
}
}
}
return arr.join('');
};
convert('QIANDUANKA', 3);
var convert = function(s, numRows) {
var cur_str = 0;
var go_down = true;
var store_obj = {};
var down_step = 0, up_step = 0;
if(numRows < 2){
return s;
}
for(var i = 0; i < numRows; i++){
store_obj[i] = '';
}
for(var k=0; k < s.length; k++){
store_obj[cur_str] = store_obj[cur_str]+s[k]+'';
if(go_down){
cur_str += 1;
down_step +=1;
if(down_step+1 == numRows){
go_down = !go_down;
down_step = 0;
}
} else {
cur_str -= 1;
up_step += 1;
if(up_step+1 == numRows){
go_down = !go_down;
up_step = 0;
}
}
}
var result = '';
Object.keys(store_obj).forEach(key => {
result += store_obj[key];
})
return result;
};
convert('QIANDUANKA', 3);
var convert = function (s, numRows) {
if (numRows === 1) return s;
let ans = '';
let cycleLen = (numRows - 1) * 2;
for (let i = 0; i < numRows; i++) {
for (let j = 0; i + j < s.length; j += cycleLen) {
ans += s[j + i];
if (i !== 0 && i !== numRows - 1 && j + cycleLen - i < s.length)
ans += s[j + cycleLen - i];
}
}
return ans;
};
convert('QIANDUANKA', 3);
前端咖,值得关注,在看哦