现在的位置: 首页 > 综合 > 正文

LeetCode题解:ZigZag Conversion

2014年01月12日 ⁄ 综合 ⁄ 共 878字 ⁄ 字号 评论关闭

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".

思路:

通过取模运算把字母放在相应的位置上。这里做了一些变通。

题解:

class Solution {
public:
    string convert(const string& s, int nrows) {
        const size_t STRLEN = s.size();
        string result;
        int modulus = nrows * 2 - 2;
        
        if  (modulus == 0)
            return result = s;
        
        // 0th row
        for (int i = 0; i < STRLEN; i += modulus)
            result.push_back (s[i]);
            
        // rows without skip
        for (int j = 1; j < modulus / 2; ++j)
            for (int i = 0; i < STRLEN; i += modulus)
            {
                if (i + j < STRLEN)
                result.push_back (s[i + j]);
                
                int oppo = i + modulus - j;
                if (oppo < STRLEN)
                    result.push_back (s[oppo]); 
            }
            
        // last row
        for (int i = nrows - 1; i < STRLEN; i += modulus)
            result.push_back (s[i]);
    
        return result;
    }
};

抱歉!评论已关闭.