C++ solution (27ms, 20lines)


  • 2
    B
    class Solution {
    public:
        string convert(string s, int nRows) {
            if (s == "" || nRows < 2) return s;
    
            int len = s.length();
            int group_len = (nRows - 1) << 1;
            int group_num = s.length() / group_len + 1;
            
            string res;
            int idx;
            for (int i = 0; i < nRows; ++i) {
                for (int j = 0; j < group_num; ++j) {
                    idx = i % group_len + j * group_len;
                    if (idx < len) res += s[idx];
                    
                    if (i == 0 || i == nRows - 1) continue;
                    
                    idx = (group_len - i) % group_len + j * group_len;
                    if (idx < len) res += s[idx];
                }
            }
            return res;
        }
    };

  • 0
    U

    what group_len means?


  • 0
    B

    Each group starts from the head of each column, end to the previous element of the next column.

    For example(the example in the quesiton):

    P A H N

    A P L S I I G

    Y I R



    Group 1 is: PAYP

    Group 2 is: ALIS


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.