My simple Java solution, really job in only one loop


  • 1
    K
    public class Solution {
        public String convert(String s, int numRows) {
            
            // Special handle
            if (s == null || s.equals("")) return "";
            
            if (numRows == 1) {
                return s;
            }
            
            // Init
            StringBuffer[] arr = new StringBuffer[numRows];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = new StringBuffer();
            }
            
            // Really job
            int li;
            for (int index = 0; index < s.length(); index++) {
                li = index % (2 * numRows - 2);
                if (li < numRows) {
                    arr[li].append(s.charAt(index));
                } else {
                    arr[2 * numRows - li - 2].append(s.charAt(index));
                }
            }
            
            // Build result
            for (int i = 1; i < arr.length; i++) {
                arr[0].append(arr[i].toString());
            }
            
            return arr[0].toString();
        }
    }
    

Log in to reply
 

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