Beat 97.88% in 5ms using Java


  • 0
    D
    public class Solution {
        public String convert(String s, int nRows) {
            int length = s.length();
            char[] ch = s.toCharArray();
            char[] newchar = new char[length];
            int p = 0;
            if(length == 1 || nRows == 1 || length <= nRows){
            	return s;
            }
            for(int i = 0;i< nRows;i++){
                if(i==0){
                    int j = 0;
                    while(2*j*(nRows-1)<length){
                        newchar[p++] = ch[(nRows-1)*2*j];
                        j++;
                    }
                }
                else if((length>=nRows) && (i == nRows-1)){
                    int j = 0;
                    while((nRows-1)*2*j+(nRows-1)<length){
                        newchar[p++] = ch[(nRows-1)*2*j+(nRows-1)];
                        j++;
                    }
                }
                else{
                    int j = 1;
                    newchar[p++] = ch[i];
                    while(((nRows-1)*2*j-i)<length){
                    	newchar[p++] = ch[(nRows-1)*2*j-i];
                    	if(((nRows-1)*2*j+i)<length){
                    		newchar[p++] = ch[(nRows-1)*2*j+i];
                    	}
                        j++;
                    }
                }
            }
            return new String(newchar);
        }
    }

Log in to reply
 

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