Straightforward java solution which you can get in a real interview


  • 0
    L
    public class Solution {
        //a straightforward solution
        public static String convert(String s, int numRows) {
            if(numRows == 1) {
                return s;
            }
            StringBuilder[] result = new StringBuilder[numRows];
            for(int i = 0; i < numRows; i++) {
                result[i] = new StringBuilder();
            }
            int currentIndex = 0;
            while (currentIndex + 2 * numRows - 3 < s.length()) {
                for (int i = 0; i < numRows; i++) {
                    result[i].append(s.charAt(currentIndex++));
                }
                for(int i = 2; i < numRows; i++) {
                    result[numRows - i].append(s.charAt(currentIndex++));
                }
            }
            int i = 0;
            while(currentIndex < s.length()) {
                if (i < numRows) {
                    result[i++].append(s.charAt(currentIndex++));
                } else {
                    result[2 * numRows - i++  - 2].append(s.charAt(currentIndex++));
                }
            }
            StringBuilder res = new StringBuilder();
            for(StringBuilder string : result) {
                res = res.append(string);
            }
            return res.toString();
    
        }
        public static void main(String[] args) {
            System.out.println(convert("PAYPALISHIRING",3));
        }
    }
    

  • 0
    L

    Sorry,ignore the main method :)


Log in to reply
 

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