9ms java solution


  • 0

    public class Solution {
    public String convert(String s, int numRows) {
    if(numRows == 1) return s;
    int n = numRows;
    StringBuilder sb = new StringBuilder();
    //first row
    for (int pos = 0; pos < s.length(); ) {
    sb.append(s.charAt(pos));
    pos += 2*(n-1);
    }
    //middle row
    for (int round = 1; round < n-1; round++) {
    for (int pos = round, k = 0; pos < s.length(); k++) {
    sb.append(s.charAt(pos));
    pos += (k%2 == 0) ? 2*(n-1-round) : 2round;
    }
    }
    //last row
    for (int pos = n-1; pos < s.length(); ) {
    sb.append(s.charAt(pos));
    pos += 2
    (n-1);
    }
    return sb.toString();
    }
    }


Log in to reply
 

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