(Beats 98.77% submissions) ZigZag Conversion in Java by NSKNGU


  • 0
    N

    This is the simplest way to find the solution for the given problem.

    class Solution {
        public String convert(String s, int numRows) {
             if (numRows == 1 || numRows == 0)
                return s;
            int n = s.length(), k = -1;  // lenth of string s
            StringBuilder result = new StringBuilder();
            int rot = 2 * numRows - 2;
            for (int i = 0; i < numRows; i++)
            {
                for (int j = i; j < n; j = j + rot)
                {
                    result.append (s.charAt (j));
                    if ( i != 0 && i != numRows - 1)
                        if ( (j + (rot - (i * 2 ))) < n)
                            result.append (s.charAt ((j + (rot - (i * 2 )))));
                }
            }
            String ans = result.toString();
            return ans;
            
        }
    }
    
    

Log in to reply
 

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