zigzag

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; 
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,490评论 0 10
  • 6. ZigZag Conversion Total Accepted: 97722Total Submissio...
    wkhuahuo阅读 527评论 0 0
  • LeetCode -- 6. ZigZag Conversion 题目描述 The string "PAYPALI...
    sea_baby阅读 477评论 0 0
  • 每日算法——letcode系列 问题 ZigZag Conversion Difficulty: Easy The...
    CarlBlack阅读 1,030评论 0 0
  • 在翻着手机吗,在想着未来吗 恋人在何方,理想是什么 翻来覆去,思前想后 逃避着,喘息着 顾虑,在乎 疼,默
    阿止止儿阅读 354评论 0 0