Accepted 7ms Simple Java Solution

• ``````public class Solution {
public String convert(String s, int numRows) {
if(numRows == 1) {
return s;
}

char[] result = new char[s.length()];
int index = 0;

for(int i = 0; i<numRows; i++) {
// first & last rows
if(i == 0 || i == numRows - 1) {
for(int j=i; j<s.length(); j+=2*(numRows-1)) {
result[index++] = s.charAt(j);
}
}
// middle rows...mirroring for index increments
else {
boolean isLeft = true;
for(int j=i; j<s.length(); ) {
result[index++] = s.charAt(j);
j += isLeft ? 2 * (numRows - 1 - i) : 2 * i;
isLeft = !isLeft;
}
}
}

return String.valueOf(result);
}
}``````

• Accepted 8ms in C language with this idea.
How you can be 7ms?

``````char* convert(char* s, int numRows) {
int strLen = strlen(s);
int k = 0, count = 0;
char *ret = malloc((strLen+1)*sizeof(char));
memset(ret,0,(strLen+1)*sizeof(char));
if (numRows >= strLen || numRows == 1){
for (int i=0; i<strLen; i++){
ret[count++] = s[i];
}
//  printf("%s",ret);
}
else{
for (; k<numRows; k++){

ret[count++] = s[k];
if (k == 0 || k == numRows-1){
int temp = k + (numRows - 1)*2;
while (temp < strLen){
ret[count++] = s[temp];
temp += (numRows - 1)*2;
}
}
else{
int temp = k;
//   int temp2 = (numRows - 1)*2 - (numRows-k-1)*2;//temp2 = 2k;
while (1){
temp += (numRows - k - 1)*2;
if (temp < strLen){
ret[count++] = s[temp];
}else break;
temp += 2*k;
if (temp < strLen){
ret[count++] = s[temp];
}else break;
}
}

}
}
ret[count] = '\0';
return ret;
``````

}

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