zigzag

作者: coder乔 | 来源:发表于2018-05-28 20:43 被阅读0次

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)

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 s, int numRows);

Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"

方法1:遍历每次首行和最后一行改变方向(所为方向就是行++和行--)

class Solution {
public:
    string convert(string s, int numRows) {
        
        if (1 >= numRows) {
            return s;
        }        
        
        int length = s.length();
        int curRow = 0;
        int direct = 1;
        
        string out[numRows];
        
        for(int i = 0; i < length; i++) {   
            out[curRow] += s[i];
            
            if(0 == curRow) {
                direct = 1;
            }
            
            if(numRows - 1 == curRow ) {
                direct = -1;
            }
            curRow += direct;
        }
    
        string result = "";  
        for(int i = 0; i < numRows; i++){  
            result += out[i];  
        }  
        return result; 
    }
};

方法2:分组,每组行数*2-2个,首行和末行各一,其余各行各2,秩序计算一下通用公式即可;

class Solution {
public:
    string convert(string s, int numRows) {
        
        if (1 >= numRows) {
            return s;
        }        
        string out = "";
        
        int length = s.length();
        int temp = 2 * numRows -2;
       
        for(int i = 0; i < numRows; i++) {   
            int curTemp = 0;
            while(curTemp * temp + i < length) {
                out += s[curTemp * temp + i];
                if(0!=i && numRows-1!=i && (curTemp+1)*temp-i<length) {
                    out += s[(curTemp+1)*temp-i];
                }
                curTemp++;
            }
        }
  
        return out; 
    }
};

相关文章

  • leetcode每日一题:(6)ZigZag Conversio

    ZigZag Conversion Question leetcode: ZigZag Conversion| L...

  • 2018-09-21

    zigzag https://leetcode-cn.com/problems/zigzag-conversion...

  • LeetCode 6 (ZigZag Conversion)

    ZigZag Conversion(ZigZag转换) 1、题目描述: The string "PAYPALISH...

  • LeetCode1.1

    ZigZag Conversion 今天题目难度中等 ZigZag Conversion 即为对角线结构。看出规律...

  • LeetCode 6. ZigZag Conversion

    ZigZag Conversion

  • LeetCode 6

    6. ZigZag Conversion 字符串“PAYPALISHIRING”,给定一个行数,使用zigzag模...

  • leetcode6

    ZigZag Conversion The string "PAYPALISHIRING" is written ...

  • zigzag

    The string "PAYPALISHIRING" is written in a zigzag patter...

  • ZigZag

    按照Z型排列字符串并且按行读取思路:存每行的字符串,最后再组合到一起因为不习惯c++的string操作,还是用ja...

  • zigzag

    zigzag算法,我觉得本质还是一维与二维转化,原始串可以看作是zigzag的特例:所有字符处在同一高度,而宽度是...

网友评论

      本文标题:zigzag

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