Java 5ms solution beats 98.77%


  • 1
    D

    public class Solution {
    public String convert(String s, int numRows) {
    char[] sArr1 = s.toCharArray();
    int length = sArr1.length;
    if(length<numRows || numRows == 1) return s;

        int singleColumn = 2*numRows - 2;
        int count = length/singleColumn;
        int remainder = length%singleColumn;
        int tempLength;
        if(remainder != 0){
            count++;
            
        }
        tempLength = count*singleColumn;
        
        int i=0;
        char[] resultArr = new char[tempLength];
        char[] sArr = new char[tempLength];
        System.arraycopy(sArr1,0,sArr,0,length);
        int j=0;
        
        int r=0;
        for(i=0;i<count;i++){
            resultArr[j] = sArr[i*singleColumn];
            j++;
        }
        char nextChar;
        for(r=1;r<numRows-1;r++){
            
            for(i=0;i<count;i++){
                nextChar = sArr[i*singleColumn+r];
                if(nextChar!='\0')
                {
                     resultArr[j] = nextChar;
                     j++;
                }
                nextChar = sArr[i*singleColumn + singleColumn-r];
                if(nextChar!='\0')
                {
                     resultArr[j] = nextChar;
                     j++;
                }
            }
            
        }
        r= numRows-1;
        for(i=0;i<count;i++){
            nextChar = sArr[i*singleColumn+r];
            
            if(nextChar!='\0')
                {
                     resultArr[j] = nextChar;
                     j++;
                }
        }
        
        System.arraycopy(resultArr,0,sArr1,0,length);
        return String.valueOf(sArr1);
    }
    

    }


  • 0
    H

    public String convert(String s, int numRows) {
    StringBuffer a = new StringBuffer();
    for (int i = 1; i <= numRows; i++) {
    if (numRows % 2 != 0) {
    if (((int) (numRows / 2) + 1) == i) {

    				for (int j = i; j < s.length()+1; j += numRows - 1) {
    					a.append(s.charAt(j-1));
    				}
    			} else {
    
    				for (int j = i; j < s.length(); j += numRows + 1) {
    					a.append(s.charAt(j-1));
    					//System.out.println(a);
    				}
    			}	
    		} else {	
    			if ((int) (numRows / 2)  == i||((int) (numRows / 2) + 1) == i) {
    
    				for (int j = i; j < s.length(); j += numRows - 1) {
    					a.append(s.charAt(j-1));
    				}
    			} else {
    
    				for (int j = i; j < s.length(); j += numRows + 1) {
    					a.append(s.charAt(j-1));
    				}
    			}
    		}
    	}
    	return a.toString();
    }

Log in to reply
 

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