O(n) java solution, esay to understand


  • 0
    R

    Create nRows StringBuffers, put characters from original string in corresponding StringBuffer.

    public String convert(String s, int numRows) {
        if (numRows <= 1)
            return s;
        List<StringBuilder> table = new ArrayList<>();
        for (int i = 0; i < numRows; i++)
            table.add(new StringBuilder());
        int x = 0, step = 1;
        for (int i = 0; i < s.length(); i++)
        {
            StringBuilder sb = table.get(x);
            sb.append(s.charAt(i));
            x += step;
            if (x == numRows - 1 || x == 0)
                step *= -1;
        }
        StringBuilder ans = new StringBuilder();
        for (int i = 0; i < table.size(); i++)
            ans.append(table.get(i));
        return ans.toString();
    }

Log in to reply
 

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