Simple, well structured, fast Java solution (beats 96%)


  • 0
    J
    public String convert(String s, int numRows) {
        
        if(numRows == 1) {
            return s;
        }
        
        StringBuilder result = new StringBuilder();
        int delta = 2;
        int maxRows = (numRows-1)*2;
        
        for(int i = 0; i < numRows; i++) {
            
            if(i == 0 || i == numRows-1) {
                appendRow(i, maxRows, maxRows, s, result);
            } else {
                appendRow(i, maxRows-delta, delta, s, result);
                delta += 2;
            }
        }
        
        return result.toString();
    }
    
    private void appendRow(int offset, int jump1, int jump2, String orig, StringBuilder sb) {
        
        int index = offset;
        int len = orig.length();
        boolean isJump1 = true;
        
        while(index < len) {
            
            sb.append(orig.charAt(index));
            index+= isJump1 ? jump1: jump2;
            isJump1 = !isJump1;
        }
    }

Log in to reply
 

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