Simple java solution for Zig Zag problem


  • 0
    public static String convert(String s, int numRows) {
    
            ArrayList<String> arr = new ArrayList<String>(numRows);
            for (int i = 0; i < numRows; i++) {
                arr.add("");
            }
    
            if(s.length()<numRows || numRows==1)
                return s;
    
            numRows--;
    
            int i=0, j=0;
            for(int k=0; k<s.length(); k++) {
                arr.set(i, arr.get(i).concat(Character.toString(s.charAt(k))));
                if(i<=numRows && j%numRows==0) {
                    if (i==numRows) {
                        i--; j++;
                    } else {
                        i++;
                    }
                } else {
                    i--; j++;
                }
    
            }
            // }
    
            String returnString = "";
            for(String st: arr) {
                returnString += st;
            }
    
            return returnString;
    
        }
    

Log in to reply
 

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