7ms Java Solution


  • 5
    W
    public class Solution {
        public String convert(String s, int numRows) {
            if (numRows == 1) {
                return s;
            }
            StringBuilder builder = new StringBuilder();
            int adder = 2*numRows-2;
            for (int i=0; i<s.length(); i+=adder) {
                builder.append(s.charAt(i));
            }
            for (int i=1; i<numRows-1; ++i) {
                int j=i;
                while(j<s.length()) {
                    builder.append(s.charAt(j));
                    int next = 2*numRows-2*i-2+j;
                    if (next < s.length())
                        builder.append(s.charAt(next));
                    else {
                        break;
                    }
                    j += adder;
                }
            }
            for (int i=numRows-1; i<s.length(); i+=adder) {
                builder.append(s.charAt(i));
            }
            return builder.toString();
        }
    }

  • 0
    D

    int a=0,b=0,c=0,d=0;
    char[] ch=s.toCharArray();
    char[] cha=new char[s.length()];
    char[][] charr=new char[numRows][7];
    for(int i=0;i<7;i++)
    {
    for(int j=0;j<numRows;j++)
    {
    if(i%2==0&&a+b<s.length())
    {
    charr[j][i]=ch[a+b];
    //cha[a+b]=charr[i][j];
    a++;
    }else
    {
    if(j%2!=0&&a+b<s.length())
    {
    charr[j][i]=ch[a+b];
    //cha[a+b]=charr[i][j];
    b++;
    }else
    {
    charr[j][i]=' ';
    }
    }
    }
    }
    for(int j=0;j<numRows;j++)
    {
    for(int i=0;i<7;i++)
    {
    if(j%2==0)
    {
    if(i%2==0&&charr[j][i]!=' '&&c+d<s.length())
    {
    cha[c+d]=charr[j][i];
    c++;
    }
    }else
    {
    if(c+d<s.length()&&charr[j][i]!=' '){
    cha[c+d]=charr[j][i];
    d++;
    }
    }

                }
            }
            return String.valueOf(cha);
        }

Log in to reply
 

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