AC Solution in Java. O(n) time and space.


  • 0
    K
    public class Solution {
        public String convert(String s, int numRows) {
            if(s.isEmpty() || numRows == 1) return s;
            StringBuffer[] strs = new StringBuffer[numRows];
            char[] ch = s.toCharArray();
            int j = 0; boolean forward = true;
            for(char c : ch) {
                if(strs[j] == null) strs[j] = new StringBuffer();
                strs[j] = strs[j].append(c);
                if(forward) j++;
                else j--;
                if(j == numRows) {
                    forward = false;
                    j = numRows - 2;
                }
                if(j == -1) {
                    forward = true;
                    j = 1;
                }
            }
            StringBuffer result = new StringBuffer();
            for(StringBuffer st : strs) { 
                if(st != null) result.append(st.toString());
            }
            return result.toString();
        }
    }
    

Log in to reply
 

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