美文网首页
6. ZigZag Conversion(之字形排列)

6. ZigZag Conversion(之字形排列)

作者: 飞飞廉 | 来源:发表于2017-12-28 15:56 被阅读0次
  1. ZigZag Conversion
    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

思路:

比如有一个字符串 “0123456789ABCDEF”,转为zigzag


image.png

除了第一行和最后一行没有形成之字形的数字外,其他的都有,不算中间的斜线部分,每行中相邻两个元素的index之差和行数是相关的,为size=2numRows-2,根据这个特点,可以按顺序找到所有黑色元素在字符串中的位置,将他们按顺序加到新字符串里。对于红色元素的位置为j+size-2i,其中j是前一个黑色元素的列数,i为当前行数。比如当n=4中的那个红色5,它的位置为1+6-2*1=5。当我们知道所有黑色元素和红色元素位置的正确算法,就可以一次性的把他们按顺序都加到新的字符串里边。

var convert = function(s, numRows) {
            if(numRows<=1) return s;
            var res='';
            var size=2*numRows-2;
            for (var i = 0; i < numRows; i++) {
                for (var j = i; j < s.length; j+=size) {
                    res+=s[j];
                    var tmp=j+size-2*i;
                    if(i!=0 && i!=numRows-1 && tmp<s.length) res+=s[tmp];
                }
            }
            return res;
        };

相关文章

网友评论

      本文标题:6. ZigZag Conversion(之字形排列)

      本文链接:https://www.haomeiwen.com/subject/obrvgxtx.html