Wrong answer? What did I do wrong here?


  • 0
    W
    Submission Result: Wrong Answer
    
    Input:	"A", 3
    Output:	"A"
    Expected:	"A"
    
    
    
    class Solution {
    public:
        string convert(string s, int nRows) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.    
            if (s.size() == 0) return "";
            if (nRows == 1) return s;
            
            stringstream ss;
            
            for(int r = 0; r < nRows; r ++) {
                if (r != nRows - 1) {
                    ss << s[r];
                }
                
                int k = 1;
                
                while (true) {
                    int up_ind = 2 * k * (nRows - 1) - r;
                    if (up_ind >= s.size()) {
                        break;
                    }
                    
                    ss << s[up_ind];
                    
                    if (r != 0 && r != nRows - 1) {
                        
                        int down_ind = 2 * k * (nRows - 1) + r;
                    
                        if (down_ind >= s.size()) {
                            break;
                        }
                        ss << s[down_ind];
                    }
                    k ++;
                }
            }
            
            return ss.str();
        }
    };

  • 2
    S

    You can consider it as Runtime Error.

    Look your code here:

        for(int r = 0; r < nRows; r ++) {
            if (r != nRows - 1) {
                ss << s[r];
            }
            ...
    

    nRows = 3 in this test case, but length of string is only 1, so the s[r] will out of range.


  • 0
    W

    Ah... Thanks


Log in to reply
 

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