A 8ms C Solution


  • 3
    X
    char* convert(char* s, int numRows) {
        int len = strlen(s);
        int i = 0, j = 0;
        int cur = 0;
        int charPerGroup = 0;
        int halfGroup = 0;
        int ngroups = 0;
    
        if(len == 0){
            return "";
        }
    
        cur = 0;
        charPerGroup = 2 * numRows - 2;
            if(charPerGroup == 0) {
            charPerGroup = 1;
        }
        
        halfGroup = charPerGroup / 2;
        ngroups = len / charPerGroup + 1;
    
        char* ret = (char*)malloc(len + 1);
    
        for(i = 0 ; i < halfGroup + 1; i++) {
            int tmp = i;
            int tmp2 = charPerGroup - i;
            if(i == 0 || i == halfGroup) {
                for(j = 0 ; j < ngroups ; j++) {
                    tmp = j * charPerGroup + i;
                    if(tmp < len) {
                        ret[cur++] = s[tmp];
                    }
                }
            } else {
                for(j = 0 ; j < ngroups ; j++) {
                    tmp = j * charPerGroup + i;
                    if(tmp < len) {
                        ret[cur++] = s[tmp];
                    }
                    tmp2 = j * charPerGroup + (charPerGroup - i);
                    if(tmp2 < len) {
                        ret[cur++] = s[tmp2];
                    }
                }
            }
        }
        ret[cur] = 0;
    
        return ret;
    }

Log in to reply
 

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