Output limit exceeded: Zigzag conversion


  • 2

    I have no idea, why my solution causes Output limit exceeded!

    class Solution {
    public:
        string convert(string s, int nRows) {
            // Input validation.
            if (nRows <= 1) return s;
            if (s.length() <= nRows) return s;
            
            int zigzag_len = nRows + nRows / 2;
            int zigzag_index = 0;
            int zigzag_head_index = 0;
            int zigzag_mid_index = 0;
            
            string result;
            for (int row = 0; row < nRows; row ++) {
                for (int index = row; index < s.length(); index += zigzag_len) {
                    if (row == 0 || row == nRows - 1) {
                        result += s[index];
                    } else {
                        result += s[index];
                        
                        zigzag_index = index / zigzag_len;
                        zigzag_head_index = zigzag_index * zigzag_len;
                        zigzag_mid_index = zigzag_len - (index - zigzag_head_index) + zigzag_head_index;
                        
                        if (zigzag_mid_index < s.length()) result += s[zigzag_mid_index];
                        
                    }
                }
            }
            return result;
        }
    };

Log in to reply
 

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