My accepted O(n) Java code without using array


  • 0
    L
    public class Solution {
    public String convert(String s, int numRows) {
        if (s != null && s.length()>0 && numRows>1){
            StringBuilder builder = new StringBuilder();
            int line = 0;
            while (line < numRows){
                boolean goDown = line<numRows-1?true:false;
                int diff = 0;
                while (line+diff < s.length()){
                    builder.append(s.charAt(line+diff));
                    if (goDown)
                        diff += 2*(numRows-1-line);
                    else
                        diff += 2*line;
                    if (line > 0 && line < numRows-1)
                        goDown = !goDown;
                }
                ++line;
            }
            return builder.toString();
        }
        return s;
    }
    }

Log in to reply
 

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